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

标签 c++ class object 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: In constructor ‘menutype::menutype(int)’:
cs163hw1.cpp:59:31: error: no matching function for call to ‘extras::extras()’
cs163hw1.cpp:59:31: note: candidates are:
cs163hw1.cpp:5:1: note: extras::extras(int)

我不明白为什么,请帮忙!

最佳答案

由于该行不应尝试调用默认构造函数(仅从 int 复制构造函数和转换构造函数),我只是猜测您有一个 extras 类型的数据成员 在你的类 menutype 中,所以你必须在初始化列表中初始化它,因为它没有默认构造函数:

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

}

关于C++构造函数调用另一个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12849070/

相关文章:

c++ dynamic_cast 装饰器实例化失败

ios - 在类方法之间匹配 2 个 NSString 值

C++ 类 : Passing a parameter

javascript - 遍历对象字面量和数组

c++ - kds with segger - 启动命令 : arm-none-eabi-gdb --version 时出错

c++ - 使用谷歌测试来检查回调

java - 使用用户输入的对象数量创建对象

java - 如何在不更改原始对象的情况下复制对象 - java

java - 修改 String/Integer 对象并检查它是否影响以该对象作为参数的类对象

c++ - msys2 静态 QT undefined reference 问题