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: 注意: 额外::额外(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)
{
}
这更有效,因为列表(额外类型)的构造函数是在初始化器列表中调用的。
相关文章:
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 如何处理没有默认构造函数但在另一个构造函数中构造的对象?
- C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?
- 让构造函数在其初始化列表中调用同一类的另一个构造函数是否有效
- 我如何在类上需要另一个构造函数的对象中声明一个对象
- 使用委托调用构造函数和在另一个构造函数体中调用的区别
- C :另一个构造函数的构造函数的隐式调用
- 从同一类的另一个构造函数调用构造函数
- 将类的实例传递给另一个构造函数,该构造函数将其对象添加到所传递实例所拥有的列表中
- C++构造函数调用另一个构造函数
- 构造具有const成员的对象时调用另一个构造函数
- 为另一个构造函数中的对象数组调用构造函数
- 在另一个构造函数中调用构造函数(没有要调用的匹配函数..) c++
- 不能从同一类的另一个构造函数调用具有所有默认参数的显式构造函数
- 为什么在添加另一个构造函数时会出现此错误
- 调用同一类中的另一个构造函数
- 在另一个构造函数中实例化的对象的构造函数内调用函数
- 是否有可能在c++中直接在另一个构造函数的参数中构造一个对象?
- 用数组初始化从另一个构造函数调用c++构造函数
- c++在同一类的另一个构造函数中调用构造函数