我有这门课
class XXX {
public:
XXX(struct yyy);
XXX(std::string);
private:
struct xxx data;
};
Run Code Online (Sandbox Code Playgroud)
第一个构造函数(使用结构)很容易实现.第二个我可以以特定格式分开一个字符串,解析并且我可以提取相同的结构.
我的问题是,在java中我可以这样做:
XXX::XXX(std::string str) {
struct yyy data;
// do stuff with string and extract data
this(data);
}
Run Code Online (Sandbox Code Playgroud)
使用this(params)调用另一个构造函数.在这种情况下,我可以类似的东西?
谢谢
您正在寻找的术语是" 构造函数委托 "(或更一般地说," 链式构造函数 ").在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 */ }
};
Run Code Online (Sandbox Code Playgroud)
如果您没有使用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 */ }
};
Run Code Online (Sandbox Code Playgroud)