[英]How to call an overloaded constructor within a constructor of the same class in c++?
我有兩個非常相關的問題; 首先,在同一類中調用重載的構造函數,其次,使用load_from_file()函數重新初始化調用對象。 這是一個例子:
class FooA: FooB
{
FooA();
FooA(myDataType distribution):FooB(distribution)
FooA(myClasstype objectA):FooA(objectA.get_distribution){} // suppose objectA has a method get_distribution().
..
...
}
它給出了一個錯誤:
非法成員初始化
第二個問題:
class FooA: FooB
{
FooA();
FooA(myDataType distribution):FooB(distribution)
void load_from_file(string file_name){
// i have another library function to load from file
JointDistribution jd = load_from_file(file_name);
// now i want to re-configure the current object
*this = FooA(jd);
}
FooA * fa =新的FooA();
fa.load_from_file(“ file_name”);
文件格式不同,因此很難將其用作構造函數。
第一個問題-如果objectA.get_distribution
是一個方法,則應該在那里調用一個方法:FooB(objectA.get_distribution())
這里:
class FooA: FooB
{
FooA();
FooA(myDataType distribution):FooB(distribution)
void load_from_file(string file_name){
}
};
函數load_from_file是私有的,因此您不能像編寫時那樣調用它:
FooA* fa = new FooA();
fa.load_from_file("file_name");
構造函數也是私有的(盡管有時我們希望它們是私有的,但我認為這里不是xD的情況)
您可以從構造函數調用構造函數:
class CComplex{
public:
CComplex(int real1,int image1)
{
real=real1;
image=image1;
const char& x='x';
CComplex(1,2,3);
}
CComplex():real(0),image(0){}
CComplex(const CComplex &c)
{
real=c.real;
image=c.image;
}
CComplex(int i1, int i2, int i3){cout<<"\n123!";}
public:
int real,image;
};
對於第一個問題,c ++ 11之前沒有構造函數委托,而您使用的語法對於c ++ 11是正確的。 只要確保已啟用c ++ 11編譯,它就可以正常工作。 如果您不能使用C ++ 11,則必須重復一些代碼。
我不明白您的第二個問題是否(關於重新加載)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.