Default constructor for an inherited class

余生颓废 提交于 2019-11-30 02:38:06

问题


I've reduced my problem down to the following example code:

class pokemon{
    public:
        pokemon(int n);
};

class MewTwo : public pokemon {
    public:
        MewTwo(int n);
};

MewTwo::MewTwo(int n) {}

Which produces an error:

no matching function for call to ‘pokemon::pokemon()’

What I think is happening is that a default constructor for pokemon is called when I try to write the MewTwo constructor, which doesn't exist. I'm relatively new to C++ so I'm just guessing here. Any ideas?

Restraint: Fixes cannot modify or add public members to the classes.


回答1:


Actually what you are looking for is the member initialization list. Change your inherited class constructor to the following:

class MewTwo : public pokemon {
    public:
        MewTwo(int n) : pokemon(n) {}
};

You were correct in identifying what was going on. Basically when you create the inherited class you first create the base class and you can't do that because there is no default constructor defined. Member initialization lists help you get around that :)

Check out : http://www.cprogramming.com/tutorial/initialization-lists-c++.html for more examples!




回答2:


Try this :

class pokemon{
    public:
        pokemon(int n);
};

class MewTwo : public pokemon {
    public:
        MewTwo(int n) :pokemon(n){}
};


来源:https://stackoverflow.com/questions/4352169/default-constructor-for-an-inherited-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!