簡體   English   中英

為什么不將其視為默認構造函數?

[英]Why is this not considered as a default constructor?

我對默認構造函數感到困惑。 我有2個代碼,代碼A和代碼B

在代碼AI中,無法理解為什么A(int news)不被視為默認構造函數,而代碼B ParentClass(int id)被視為默認構造函數

為什么代碼A不能編譯而代碼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();
}

編輯后,問題終於清楚了。 重新措辭我的答案。

前言。 在C ++中,默認構造函數是不帶參數的構造函數,或者所有參數都具有默認值的構造函數。 沒有提供其他信息時,它用於創建對象。 例如,

Default a;
Default* p = new A; 

在上面的代碼中,調用了Default默認構造函數。

在這個例子中A你想調用默認的構造函數A -因為A a調用A的默認構造函數。 由於此類構造函數不存在,因此會出現編譯錯誤。 您擁有的唯一構造函數是一個采用整數參數的構造函數,您可以使用以下代碼對其進行調用:

A a(42);

在第二個示例中,您正在調用ChildClass 默認(用戶提供)構造函數-因為ChildClass c(1)調用了一個接受一個整數參數的ChildClass構造函數-就是這樣。 順便說一句,此ChildClass構造函數調用ParentClass構造函數,該構造函數僅接受一個整數參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM