[英]C++ constructor call another constructor based on parameter type
我有这门课
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 ++ 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 */ }
};
是。 在C ++ 11中,您可以这样做。 它被称为构造函数委托 。
struct A
{
A(int a) { /* code */ }
A() : A(100) //delegate to the other constructor
{
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.