我有这门课
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);
}
Using this(params)
调用另一个构造函数。在这种情况下我可以做类似的事情吗?
Thanks
您要查找的术语是“构造函数委托 http://en.wikipedia.org/wiki/C%2B%2B11#Object_construction_improvement“(或者更一般地说,”链式构造函数")。在 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 */ }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)