开发者

Default constructor for an inherited class

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开发者_JS百科'm just guessing here. Any ideas?

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


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!


Try this :

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜