开发者

Unable to create class instance

开发者 https://www.devze.com 2023-04-08 11:28 出处:网络
I have a singleton class that implements two other abstract classes. My monkey::getMonkey fails because of thisMonkey = new monkey() returns \"object of abstract class type \"monkey\" is not allowed\

I have a singleton class that implements two other abstract classes.

My monkey::getMonkey fails because of thisMonkey = new monkey() returns "object of abstract class type "monkey" is not allowed". I know you cannot instantiate abstract classes, but my monkey implements two abstract classes (meaning it is not abstract.. right?)

What is a solution to this?

class monkey : public animal,
               public npc {
public:
    ~monkey();
    static monkey* getMonkey();

private:
    monkey();
    static monkey* thisMonkey;

}




monkey::monkey() {};

monkey::~monkey() {};

/* .. implements the virtual methods of animal and npc ... */

monkey::getMonkey() {
    if (!thisMonkey)
        thisMonkey = new 开发者_开发百科monkey();
    return thisMonkey;
}


You don't show enough to say exactly, but a priori, your class monkey doesn't implement all of the pure virtual functions in the base class. A class which has pure virtual functions which haven't been overridden is abstract.


Find all the the methods declared pure-virtual in the classes anmial and npc and provide implementations for them within the monkey class. They are base classes of the monkey class, and it appears that you haven't fulfilled their abstract interface.

Pure virtual classes look like:

return_type methodName(params)=0;

You must provide a function in the derived class (monkey) with that exact prototype, with an implementation. This will be called when you have a pointer to one of the derived classes and call that "pure-virutal" function. I.e.

 animal* aptr = new monkey;
 aptr->methodName(params);

will map to:

monkey::methodName
0

精彩评论

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

关注公众号