斗士狗 2008-11-21 09:43 采纳率: 0%
浏览 484
已采纳

在 c + + 中,我可以从另一个构造函数(执行构造函数链接)调用构造函数吗?

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

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

    public Test(int count) : this() {
        DoSomethingWithCount(count);
    }

    public Test(int count, string name) : this(count) {
        DoSomethingWithName(name);
    }
}

Is there a way to do this in C++?

I tried calling the Class name and using the 'this' keyword, but both fails.

转载于:https://stackoverflow.com/questions/308276/can-i-call-a-constructor-from-another-constructor-do-constructor-chaining-in-c

  • 写回答

15条回答 默认 最新

  • Memor.の 2008-11-21 10:04
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog