nakka soft world !

생성자 (construct) 본문

프로그래밍언어/C++

생성자 (construct)

nakka 2017. 3. 16. 23:07
728x90

class Point

{

private:

int x;

int y;

public:

Point() {cout << "Point()" << endl; }   // 1

Point(int a, int b) {cout << "Point(int,int)" << endl; }  // 2

}


int main()

{

Point p1;  // 2만 있으면 Error, 1이 있으면 정상 빌드, 아무것도 없어도 정상빌드.

Point p2(1,1);  // 2가 주석처리 되면 Error.

Point p3(1); // 동일한 형태의 생성자 없으므로 Error.

}

사용자가 생성자를 만들지 않는 다면 컴파일러가 만들어줌. - 디폴트 생성자

인자 없고, 아무짓도 안함.


class Point

{

private:

int x;

int y;

public:

Point() {cout << "Point()" << endl; }   // 1

Point(int a, int b) {cout << "Point(int,int)" << endl; }  // 2

}

int main()

{

Point p1;  // 1

Point p2(1,2);  // 2


Point p3[10]; // 1번 생성자 10회 호출

Point p4[10] = { Point(1,1), Point(0,0)}; // 2번 생성자 2회 호출, 1번 생성자 8회 호출


Point* p5; // 생성자 호출안됨

Point* p6 = static_cast<Point*>(malloc(sizeof(Point)));   // 생성자 호출안됨

Point* p7 = new Point;  // 1번생성자 호출

Point* p7 = new Point(1,1);  // 2번생성자 호출

}



class Point

{

private:

int x;

int y;

public:

Point() {cout << "Point()" << endl; }   // 1

Point(int a, int b) {cout << "Point(int,int)" << endl; }  // 2

}

class Rect

{

private:

Point p1;

Point p2;

public:

Rect() { cout << "Rect()" << endl; }

}
int main()

{

Rect r; // Point의 생성자도 불림. 단, 멤버의 생성자가 먼저 불리고, 자기자신의 생성자가 다음에 불림.

}

728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

소멸자  (0) 2017.03.16
default function, delete function  (0) 2017.03.16
접근 지정자  (0) 2017.03.16
making stack  (0) 2017.03.16
OOP Concept  (0) 2017.03.16
Comments