问题描述
我有这个类
class XXX {
public:
XXX(struct yyy);
XXX(std :: string);
private:
struct xxx data;
}
第一个构造函数第二个我可以以特定的格式,一个字符串,解析,我可以提取相同的结构。
我的问题是,在java我可以这样做: / p>
XXX :: XXX(std :: string str){
struct yyy data;
//使用字符串和提取数据进行操作
this(data);
}
使用 this(params)
调用另一个构造函数。
class Foo {
public:
Foo(int x):Foo(){
/ *具体构造在这里* /
}
Foo(string x):Foo这里* /
}
private:
Foo(){/ *常见构造在这里* /}
};
如果你不使用C ++ 11,最好的方法是定义一个私人助手函数来处理所有构造函数共有的东西(虽然这是令人讨厌的东西,你想放入初始化列表)。例如:
class Foo {
public:
Foo(int x){
/ *具体构造在这里* /
ctor_helper();
}
Foo(string x){
/ *具体构造在这里* /
ctor_helper();
}
private:
void ctor_helper(){/ * Commonconstructionhere here * /}
};
I have this class
class XXX {
public:
XXX(struct yyy);
XXX(std::string);
private:
struct xxx data;
};
The first constructor (who works with a structure) is easy to implement. The second I can parte one string in a specific format, parse and I can extract the same structure.
My question is, in java I can do something like this:
XXX::XXX(std::string str) {
struct yyy data;
// do stuff with string and extract data
this(data);
}
Using this(params)
to call another constructor. In this case I can something similar?
Thanks
The term you're looking for is "constructor delegation" (or more generally, "chained constructors"). Prior to C++11, these didn't exist in C++. But the syntax is just like invoking a base-class constructor:
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 */ }
};
If you're not using C++11, the best you can do is define a private helper function to deal with the stuff common to all constructors (although this is annoying for stuff that you'd like to put in the initialization list). For example:
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 ++构造函数根据参数类型调用另一个构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!