2013-01-06 97 views
5

另一个构造我有这个类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

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

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

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

您是否知道哪些编译器目前正在实施此更改,我似乎记得Clang并未(例如)。 –

+0

@MatthieuM .:我不知道。没有用任何编译器测试过它。 :-) – Nawaz

+0

:)恐怕这在实践中并不被认为是重要的,因为对私有方法的授权已经非常成功(只要所有属性都支持赋值),因此对每个人来说都是低优先级。 –

8

你要找的术语是 “constructor delegation”(或者更一般地, “链构造”)。在C++ 11之前,这些在C++中不存在。但语法就像调用基类的构造函数:如果你不使用C++ 11,你能做的最好的是定义一个私有的辅助函数来处理共同所有的东西

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 */ } 
}; 

构造函数(虽然这是烦人的东西,你想放在初始化列表中)。例如:

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 */ } 
}; 
+0

我提高你的答案,因为它更完整。但例子会非常好。 :-) – Omnifarious

+2

@Omnifarious:示例现在存在! –

相关问题