본문 바로가기
카테고리 없음

[C/C++] 생성자

by 일사만루병살 2011. 1. 27.
객체를 생성할 때 초기값을 줄 수 있도록 하는 것이 생성자이다.
그러므로 객체가 생성될 때 멤버변수에 특정한 값을 저장하려면 컴파일러가 제공하는 디폴트 생성자 대신 프로그래머가 매개변수가 없는 생성자를 재정의해 주어야 한다.

매개변수가 없는 생성자.
#include <iostream>
using namespace std;

class Complex
{
private :
int real;
int image;
public :
Complex(); //생성자 선언
void ShowComplex() const;
};

Complex::Complex()//생성자도 함수 이기 때문에
{ //프로그래머가 생성자를 쓰기 위해서는
real = 5;         //선언과 정의를 해줘야 한다.
image = 20;
}

void Complex::ShowComplex() const
{
cout<<real<<"\t"<<image<<endl;
}

void main()
{
Complex x;
x.ShowComplex();
}


매개변수를 가지는 생성자
#include <iostream>
using namespace std;

class Complex
{
private :
int real;
int image;
public :
Complex(int x, int y); //생성자 선언
void ShowComplex() const;
};

Complex::Complex(int x, int y)//생성자도 함수 이기 때문에
{               //프로그래머가 생성자를 쓰기 위해서는
real = x;                       //선언과 정의를 해줘야 한다.
image = y;
}

void Complex::ShowComplex() const
{
cout<<real<<"\t"<<image<<endl;
}

void main()
{
Complex x(100,200);
x.ShowComplex();
}