생성자와 소멸자

|
생성자
클래스와 동일한 이름
반환 값이 없다.
객체가 생성될 때 자동으로 호출된다.
생성자를 작성하지 않으면 기본 생성자가 자동으로 호출된다. Class::Class() {}
Point::Point() { _x = 0; _y = 0; }
Point pt;
Point pt = Point();

디폴트 생성자
인자가 없는 생성자 Class::Class() { initialize code; }
Point pt;
Point pt = Point();

인자가 있는 생성자
Point::Point(int x, int y) {_x = x; _y = y; }
Point pt(10, 20);

복사 생성자
자신과 동일한 타입의 객체에 대한 레퍼런스를 인자로 받는 생성자.
Class::Class(Class& c) { intialize code; }
Class::Class(const Class& c) { intialize code; } 권장
Point::Point(const Point& pt) { x = pt.x; y = pt.y; }
Point pt1;
Point pt2 = pt1; (초기화 문법 이용)
Point pt2(pt1); (생성자 호출 문법 이용)
*초기화 : 생성과 동시에 값을 대입하는 것???
Point pt1;
Point pt2;
pt2 = pt1; 복사 생성자가 호출되지 않고, 멤버변수를 1:1로 복사한다.

class string
{
private:
char* p;
public:
string(const string& s);
int size() const
{
return strlen(p);
}
...

Shallow Copy
string::string(const string& s) { p = s.p; }
string str1;
string str2(str1);
str1 객체의 문자열의 시작 주소만 복사된다. str1 객체가 소멸되면 str1이 가리키고 있던 문자열도 소멸되므로 str2는???
Deep Copy
string::string(const string& s) { p = new char[s.Size() + 1]; strcpy(p, s.p);
string str1;
string str2(str1);
str1 객체의 문자열 자체를 복사한다. str1 객체가 소멸되어도 str2 객체는 새로 생성된 문자열의 시작주소를 가리키므로 문제없다.

반드시 생성자가 필요한 경우 : const, &
const : 한 번 정의된 이후에는 값을 변경할 수 없으므로 반드시 초기화하여 그 값만을 가져야 한다.
& : 처음 정의할 때 참조한 변수 이외의 다른 변수는 참조할 수 없으므로 반드시 초기화해야 한다.

class NeedConstructor
{
public:
const int maxCount;
int& ref;
int sample;

NeedConstructor();
NeedConstructor(int count, int& number);
};

NeedConstructor::NeedConstructor()
: maxCount(100), ref(sample)
{
sample = 200;
}

NeedConstructor::NeedConstructor(int count, int& number)
: maxCount(count), ref(number0
{
sample = 200;
}

생성자를 이용한 임시 객체
void Func(const Point& pt)
{
...
}
Func(Point(x, y));

소멸자
DynamicArray::DynamicArray(int arraySize)
{
arr = new int [arraySize];
}

DynamicArray::~DynamicArray()
{
delete [] arr;
arr = NULL;
}

main() 죵료시 함수 내의 객체도 소멸되므로 소멸자를 호출하고 이 때 메모리를 해제한다. 













import android.view.View.oonclickelisterne;

setContentView(R.laout.hello_layout);

EditText edittext = (EditiText)this.findViewById(R.id.EditText01);
Button button = (button)this.findViewById(R.id....);
button.setonclickelistenter(new onclicklistener() {

 } )

public onClick(View arg0) {
edittext.setText("버튼 눌러짐"); << final 처리 변수 -- final EditText edit~~~

'C++' 카테고리의 다른 글

다중 상속의 문제점  (0) 2010.08.16
C++ 생성자  (0) 2010.08.13
c++ 오버라이딩  (0) 2010.07.03
동적 할당 0614  (0) 2010.06.14
c++ 0610  (0) 2010.06.10
And