생성자 안에서 생성자 부르기

조회수 6299회

C#개발 할 때는 밑의 코드처럼 썼었는데 C++에서는 어떻게 하는지 궁금합니다. 클래스 이름을 부르려고 this() 썼는데 안 된다고 나오네요 왜죠

소스코드

class Test {
public:
    Test() {
        //DoSomething
    }
    Test(int count) : this() {
        //DoSomething
    }
    Test(int count, string name) : this(count) {
        //DoSomething
    }
};

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    C++11 이상에서는 생성자 안에서 다른 생성자를 부를 수 있습니다 C#이랑은 문법이 좀 달라요

    class Test {
    public:
        Test() {
            //DoSomething
        }
        Test(int count) : Test() {
            //DoSomething
        }
        Test(int count, string name) : Test(count){
            //DoSomething
        }
    };
    

    이런 식으로 쓰시면 됩니다.

    C++03를 쓰시는 경우라면 위에 코드는 지원이 안되니까 비슷하게 하려면 다음의 방법이 있습니다.

    디폴트 파라미터를 통해 2개 이상의 생성자 합치기

    class Test {
    public:
        //Test(int)와 Test(int, string) 지원
        Test(int count, string name=NULL){
            //DoSomething
        }
    };
    

    init메소드를 만들어서 생성자에서 호출하기

    class Test {
    public:
        Test() {
            init();
        }
        Test(int count) : Test() {
            init(count);
        }
        Test(int count, string name=NULL){
            init(count, name);
        }
    private:
        void init() {}
        void init(int count) { init(); }
        void init(int count, string name) { init(count); }
    };
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)