Can I call a constructor from another constructor (do constructor chaining) in C++?

前端 未结 15 2493
暖寄归人
暖寄归人 2020-11-22 01:27

As a C# developer I\'m used to running through constructors:

class Test {
    public Test() {
        DoSomething();         


        
15条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 01:55

    Another option that has not been shown yet is to split your class into two, wrapping a lightweight interface class around your original class in order to achieve the effect you are looking for:

    class Test_Base {
        public Test_Base() {
            DoSomething();
        }
    };
    
    class Test : public Test_Base {
        public Test() : Test_Base() {
        }
    
        public Test(int count) : Test_Base() {
            DoSomethingWithCount(count);
        }
    };
    

    This could get messy if you have many constructors that must call their "next level up" counterpart, but for a handful of constructors, it should be workable.

提交回复
热议问题