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

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

    C++11: Yes!

    C++11 and onwards has this same feature (called delegating constructors).

    The syntax is slightly different from C#:

    class Foo {
    public: 
      Foo(char x, int y) {}
      Foo(int y) : Foo('a', y) {}
    };
    

    C++03: No

    Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:

    1. You can combine two (or more) constructors via default parameters:

      class Foo {
      public:
        Foo(char x, int y=0);  // combines two constructors (char) and (char, int)
        // ...
      };
      
    2. Use an init method to share common code:

      class Foo {
      public:
        Foo(char x);
        Foo(char x, int y);
        // ...
      private:
        void init(char x, int y);
      };
      
      Foo::Foo(char x)
      {
        init(x, int(x) + 7);
        // ...
      }
      
      Foo::Foo(char x, int y)
      {
        init(x, y);
        // ...
      }
      
      void Foo::init(char x, int y)
      {
        // ...
      }
      

    See the C++FAQ entry for reference.

提交回复
热议问题