C ++构造函数基于参数类型调用另一个构造函数

时间:2013-01-06 16:06:35

标签: c++

我有这个班级

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)调用另一个构造函数。在这种情况下,我可以类似的东西?

由于

2 个答案:

答案 0 :(得分:8)

您正在寻找的术语是“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 */ }
};

答案 1 :(得分:2)

是。在C ++ 11中,您可以这样做。它被称为constructor delegation

struct A
{
   A(int a) { /* code */ }

   A() : A(100)  //delegate to the other constructor
   {
   }
};