【问题标题】:C++ constructor call another constructor based on parameter typeC++构造函数根据参数类型调用另一个构造函数
【发布时间】:2013-01-06 16:06:35
【问题描述】:

我有这门课

class XXX {
    public:
        XXX(struct yyy);
        XXX(std::string);
    private:
        struct xxx data;
};

第一个构造函数(使用结构)很容易实现。第二个我可以以特定格式分割一个字符串,解析并提取相同的结构。

我的问题是,在 java 中我可以这样做:

XXX::XXX(std::string str) {

   struct yyy data;
   // do stuff with string and extract data
   this(data);
}

使用this(params) 调用另一个构造函数。在这种情况下,我可以做类似的事情吗?

谢谢

【问题讨论】:

    标签: c++


    【解决方案1】:

    您要查找的术语是“constructor delegation”(或更一般地说,“链式构造函数”)。在 C++11 之前,这些在 C++ 中不存在。但语法就像调用基类构造函数:

    class Foo {
    public:
        Foo(int x) : Foo() {
            /* Specific construction goes here */
        }
        Foo(string x) : Foo() {
            /* Specific construction goes here */
        }
    private:
        Foo() { /* Common construction goes here */ }
    };
    

    如果你不使用 C++11,你能做的最好的事情就是定义一个私有帮助函数来处理所有构造函数共有的东西(尽管这对于你想要放入初始化列表)。例如:

    class Foo {
    public:
        Foo(int x) {
            /* Specific construction goes here */
            ctor_helper();
        }
        Foo(string x) {
            /* Specific construction goes here */
            ctor_helper();
        }
    private:
        void ctor_helper() { /* Common "construction" goes here */ }
    };
    

    【讨论】:

    • 我赞成您的回答,因为它更完整。但是例子会很好。 :-)
    • @Omnifarious:现在有例子!
    【解决方案2】:

    是的。在 C++11 中,您可以做到这一点。它被称为constructor delegation

    struct A
    {
       A(int a) { /* code */ }
    
       A() : A(100)  //delegate to the other constructor
       {
       }
    };
    

    【讨论】:

    • 你知道哪些编译器目前实现了这个改变,我似乎记得 Clang 没有(还)例如。
    • @MatthieuM.:我不知道。尚未使用任何编译器对其进行测试。 :-)
    • :) 恐怕这在实践中被认为不那么重要,因为委托给私有方法已经非常有效(只要所有属性都支持分配),因此对于每个人来说都是低优先级.
    • @MatthieuM.:反正我不使用很多构造函数;-)。只有框架通常在一个类中有许多构造函数。所以这可能是另一个原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2014-08-01
    • 1970-01-01
    • 2014-03-12
    • 2017-01-05
    • 2012-07-28
    • 2012-06-22
    相关资源
    最近更新 更多