[英]Can constructor call another class's constructor in c++?
class A {
public:
A(int v) {
_val = v;
}
private:
int _val;
};
class B {
public:
B(int v) {
a = A(v); // i think this is the key point
}
private:
A a;
};
int main() {
B b(10);
return 0;
}
編譯說:
test.cpp: In constructor ‘B::B(int)’:
test.cpp:15: error: no matching function for call to ‘A::A()’
test.cpp:5: note: candidates are: A::A(int)
test.cpp:3: note: A::A(const A&)
我已經學習了Java,我不知道如何在C ++中處理這個問題。 搜索了幾天,PLZ告訴我C ++可以這樣做嗎?
您需要使用成員初始化列表
B(int v):a(v)
{
}
附:
B(int v)
{
a = A(v); // i think this is the key point
}
a
被分配了一個值而沒有被初始化 ( 這是你想要的 ),一旦構造函數的主體開始{
,它的所有成員都已經被構造。
為什么會出錯?
編譯器構造a
before構造函數體{
開始,編譯器使用A
的無參數構造函數,因為你沒有告訴它,否則注1 ,因為默認的無參數構造函數不可用因此錯誤。
為什么不隱式生成默認的無參數構造函數?
一旦為類提供了任何構造函數,就不再生成隱式生成的無參數構造函數。 您為A
構造函數提供了重載,因此沒有隱式生成無參數構造函數。
注1
使用Member Initializer List是告訴編譯器使用構造函數的特定重載版本而不是默認的無參數構造函數的方法。
您必須使用初始化列表:
class B {
public:
B(int v) : a(v) { // here
}
private:
A a;
};
否則編譯器將嘗試使用默認構造函數構造A
由於您沒有提供,因此會出現錯誤。
是的它可以,但是您沒有為A
提供默認構造函數(沒有參數或所有參數都有默認值),因此您只能在初始化列表中初始化它:
B(int v) : a(v)
{
}
這是因為構造體進入之前, a
將構造(或試圖構建)用默認構造(這是不可用)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.