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

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

    This approach may work for some kinds of classes (when the assignment operator behaves 'well'):

    Foo::Foo()
    {
        // do what every Foo is needing
        ...
    }
    
    Foo::Foo(char x)
    {
        *this = Foo();
    
        // do the special things for a Foo with char
        ...
    }
    

提交回复
热议问题