생성자도 함수의 일종이다. 따라서 오버로딩이 가능하다.

또한 매개변수에 '디폴트 값'을 설정할 수 있다.


#include <iostream>
using namespace std;

class TestClass
{
private:
    int num1;
    int num2;
public:
    /*TestClass()
    {
        num1=0;
        num2=0;
    }
    TestClass(int a)
    {
        num1=a;
        num2=0;
    }
    TestClass(int a, int b)
    {
        num1=a;
        num2=b;
    }
    */


    TestClass(int a=0, int b=0)
    {
        num1=a;
        num2=b;
    }
    

    void Show() const
    {
        cout<<num1<<" "<<num2<<endl;
    }
};

int main()
{
    TestClass test1;
    test1.Show();

    TestClass test2(100);
    test2.Show();

    TestClass test3(200,300);
    test3.Show();

    return 0;
}


위 코드에서 주석 처리 된 부분은 오버로딩을 통한 생성자이다. 그런데 여기서는 아래와 같은 생성자를 사용하였는데


TestClass(int a=0, int b=0)
    {
        num1=a;
        num2=b;
    }


이것은 매개변수의 디폴트 값을 정해준 형태이다.


이때 멤버 변수를 초기화할 때 멤버 이니셜라이저를 이용할 수 있다.


TestClass(int a=0, int b=0):num2(b)
    {
        num1=a;
       // num2=b;
    }


num2(b)의 의미는 num2=b와 같다.

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

상속의 이해  (0) 2014.02.06
복사 생성자  (0) 2013.09.06
explicit 예제  (0) 2013.09.06
두 개의 Circle 클래스를 기반으로 한 Ring 클래스 생성  (0) 2013.08.22
난수 사용하기  (0) 2013.07.25
참조자와 함수의 호출관계  (0) 2013.07.24
new & delete 기본 사용법  (0) 2013.07.23

+ Recent posts