class SimpleClass
{
private:
int num;
public:
SimpleClass(int n)
{
num = n;
}
int GetNum() const
{
return num;
}
}
위의 클래스 정의에서 다음의 형태를 띠는 함수가 있다.
이러한 유형의 함수를 가리켜 ‘생성자(constructor)’라 하며, 이는 다음의 특징을 갖는다.
“객체 생성시 딱 한번 호출된다.”
SimpleClass sc;
SimpleClass *ptr = new SimpleClass;
//생성자 정의 후
SimpleClass cs(20);
SimpleClass *ptr = new SimpleClass(30);
SimpleClass sc(); (x)
위는 함수의 원형과 같다. C++ 이러한 함수호출을 금지한다.
class Rectangle
{
private:
Point upLeft;
Point lowRight;
public:
Rectangle(const int &x1, const int &y1, const int &x2, const int &y2);
void ShowRecInfo() const;
}
Rectangle::Rectangle(const int &x1, const int &y1, const int &x2, const int &y2)
::upLeft(x1, y1), lowRight(x2, y2)
{
//empty
}
//::upLeft9x1, y1), lowRight(x2, y2)
마지막으로 우리는 객체의 생성과정을 다음과 같이 정리할 수 있다.
class SoSimple
{
private:
int num1;
int num2;
public:
SoSimple(int n1, int n2) : num1(n1)
{
num2=n2;
}
...
}