C++构造函数调用另一个构造函数

C++ constructor calling another constructor

本文关键字:另一个 构造函数 函数调用 C++      更新时间:2023-10-16

尝试构建包含以下代码的 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: 注意: 额外::额外(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) {}

正如其他人所说,您错误地调用了构造函数。

另外三个人已经指出了正确的初始值设定项列表方法。但是,没有人指出如何在构造函数上下文之外正确调用构造函数。

而不是:

extras list = extras(cat_num);

做:

extras list(cat_num);
通常按

以下方式调用另一个类的构造函数中的构造函数(如示例中所示):

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

这更有效,因为列表(额外类型)的构造函数是在初始化器列表中调用的。