C++
소멸자
GOD03219
2018. 9. 12. 15:32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 |
#include<iostream>
#include<string.h>
#include<cstdlib>
using namespace std;
/*
소멸자 : 객체 소멸 시 자동호출
public으로 만들어야 한다. 외부에서 객체를 소멸할 수 있게 객체 등록 해제
생성자와 동일하지만 함수명 앞에 ~(틸드)가 붙는다.
오버로딩이 불가능하다.
const member function으로 만들 수 없다.
virtual 함수로 꼭 만들어서 사용해야 한다. (동적바인딩을 위해서)
*/
class Obj{
int a;
public:
Obj(int a=0){this->a=a;}
~Obj() { cout << "소멸자"<<endl; } // 소멸자 함수
int getA(){
return a;
}
};
void main(){
Obj obj;
Obj obj2(100);
cout << obj. getA() << endl;
cout << obj2. getA() << endl;
} |
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 |
#include<iostream>
#include<string.h>
#include<cstdlib>
using namespace std;
class Obj{
int a;
public:
Obj(int a=0){this->a=a;}
~Obj() { cout << "소멸자"<<endl; }
int getA(){
return a;
}
};
void main(){
Obj *p = new Obj;
delete p; // 동적메모리로 객체 할당 시 delete 해줘야 Obj 클래스의 소멸자 함수 호출
}
|
cs |