简体   繁体   English

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

[英]C++ constructor calling another constructor

When attempting to build a c++ program containing the following code: 尝试构建包含以下代码的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));
    }
}

I receive the error : 我收到错误:

cs163hw1.cpp: In constructor 'menutype::menutype(int)': cs163hw1.cpp:在构造函数'menutype :: menutype(int)'中:
cs163hw1.cpp:59:31: error: no matching function for call to 'extras::extras()' cs163hw1.cpp:59:31:错误:没有匹配的函数可调用'extras :: extras()'
cs163hw1.cpp:59:31: note: candidates are: cs163hw1.cpp:59:31:注意:候选人为:
cs163hw1.cpp:5:1: note: extras::extras(int) cs163hw1.cpp:5:1:注意:Extras :: extras(int)

And I do not understand why, please help! 而且我不明白为什么,请帮忙!

Since that line shouldn't attempt to call a default constructor (only copy constructor and conversion constructor from int ), I'll just guess that you have a data member of type extras in your class menutype , so you have to initialize it in the initializer list because it doesn't have a default constructor: 由于该行不应尝试调用默认构造函数(仅从int复制副本构造函数和转换构造函数),因此我只能猜测您的类menutype有一个类型为extras的数据成员,因此您必须在初始化列表,因为它没有默认的构造函数:

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

}

It seems like your menutype holds a member of type extras . 看来您的menutype拥有extras类型的成员。 If that is the case, and if extras does not have a default constructor (as it seems to be the case) you need to initialize it in the initialization list: 如果是这样,并且extras没有默认构造函数(似乎是这种情况),则需要在初始化列表中对其进行初始化:

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

One would typically call a constructor within a constructor of another class (as in your example) the following way: 通常,您可以通过以下方式在另一个类的构造函数中调用构造函数(例如您的示例):

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

This is more efficient as the constructor for list (of type extra) is called in the initialiser list. 由于在初始化程序列表中调用了list(额外类型)的构造函数,因此效率更高。

As others said, you are calling the constructor incorrectly. 正如其他人所说,您在错误地调用构造函数。

Three other people have already pointed out the proper initializer list method. 其他三个人已经指出了正确的初始化列表方法。 However, no one has pointed out how to properly call a constructor outside of a constructor context. 但是,没有人指出如何在构造函数上下文之外正确调用构造函数。

Instead of: 代替:

extras list = extras(cat_num);

Do: 做:

extras list(cat_num);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM