[英]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.