简体   繁体   中英

C++ constructor calling another constructor

When attempting to build a c++ program containing the following code:

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: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)

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:

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 . 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:

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.

As others said, you are calling the constructor incorrectly.

Three other people have already pointed out the proper 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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