簡體   English   中英

C ++構造函數調用另一個構造函數

[英]C++ constructor calling another constructor

嘗試構建包含以下代碼的c ++程序時:

menutype::menutype(int cat_num){
    extras list = extras(cat_num);
}

extras::extras(int num_cats){
    head = new category_node;
    head->next = NULL;
    head->category = 1;
    category_node * temp;
    for(int i = 1; i < (num_cats); ++i){
        temp = new category_node;
        temp->next = head->next;
        head->next = temp;
        temp->category = (num_cats-(i-1));
    }
}

我收到錯誤:

cs163hw1.cpp:在構造函數'menutype :: menutype(int)'中:
cs163hw1.cpp:59:31:錯誤:沒有匹配的函數可調用'extras :: extras()'
cs163hw1.cpp:59:31:注意:候選人為:
cs163hw1.cpp:5:1:注意:Extras :: extras(int)

而且我不明白為什么,請幫忙!

由於該行不應嘗試調用默認構造函數(僅從int復制副本構造函數和轉換構造函數),因此我只能猜測您的類menutype有一個類型為extras的數據成員,因此您必須在初始化列表,因為它沒有默認的構造函數:

menutype::menutype(int cat_num) : list(cat_num) { //or whatever the member is called

}

看來您的menutype擁有extras類型的成員。 如果是這樣,並且extras沒有默認構造函數(似乎是這種情況),則需要在初始化列表中對其進行初始化:

menutype::menutype(int cat_num) : myextrasmember(cat_num) {}

通常,您可以通過以下方式在另一個類的構造函數中調用構造函數(例如您的示例):

menutype::menutype(int cat_num) : list(cat_num) { }

由於在初始化程序列表中調用了list(額外類型)的構造函數,因此效率更高。

正如其他人所說,您在錯誤地調用構造函數。

其他三個人已經指出了正確的初始化列表方法。 但是,沒有人指出如何在構造函數上下文之外正確調用構造函數。

代替:

extras list = extras(cat_num);

做:

extras list(cat_num);

暫無
暫無

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

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