이 튜토리얼에서는 C++의 생성자를 이해하는 프로그램에 대해 논의할 것입니다.
생성자는 객체 인스턴스 생성을 시작하는 클래스의 멤버 함수입니다. 부모 클래스와 이름이 같으며 반환 유형이 없습니다.
기본 생성자
예시
#include <iostream>
using namespace std;
class construct {
public:
int a, b;
//default constructor
construct(){
a = 10;
b = 20;
}
};
int main(){
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
} 출력
a: 10 b: 20
매개변수화된 생성자
예시
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int x1, int y1){
x = x1;
y = y1;
}
int getX(){
return x;
}
int getY(){
return y;
}
};
int main(){
Point p1(10, 15);
cout << "p1.x = " << p1.getX() << ", p1.y = " <<
p1.getY();
return 0;
} 출력
p1.x = 10, p1.y = 15