我混淆了默認的構造函數。 我有2碼,代碼A和代碼B爲什麼這不被視爲默認的構造函數?
在代碼。我不明白爲什麼A(int news)
不被視爲默認的構造函數,而代碼B ParentClass(int id)
是考慮作爲默認的構造函數
爲什麼代碼中的ISN」能夠編譯但代碼B能夠編譯。
碼A
class A{
public:
int s;
A(int news){
s = news;
}
void print()
{
cout << s;
}
};
int main()
{
A a;
a.print();
}
代碼B
class ParentClass{
public:
int id;
ParentClass(int id){
this->id = id;
}
void print(){
cout << id <<endl;
}
};
class ChildClass:public ParentClass
{
public:
int id;
ChildClass(int id):ParentClass(1)
{
this->id = id;
}
};
int main()
{
ChildClass c(2);
c.print();
}
所以代碼A有一個非默認的構造函數嗎?爲什麼當我運行它時,它會說沒有默認構造函數?而代碼B則會運行。 – overflowhow
@overflowhow,你要運行哪個* code *? – SergeyA
我的意思是,如果我運行代碼A,它會給出錯誤,說默認的構造函數沒有定義。但是,當我運行代碼B它運行成功..另一個問題,是必須有默認的構造函數? – overflowhow