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

前端 未结 15 2509
暖寄归人
暖寄归人 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:31

    No, you can't call one constructor from another in C++03 (called a delegating constructor).

    This changed in C++11 (aka C++0x), which added support for the following syntax:
    (example taken from Wikipedia)

    class SomeType
    {
      int number;
    
    public:
      SomeType(int newNumber) : number(newNumber) {}
      SomeType() : SomeType(42) {}
    };
    

提交回复
热议问题