无法创建类实例

发布于 2024-12-06 02:10:30 字数 607 浏览 1 评论 0原文

我有一个单例类,它实现了另外两个抽象类。

我的 Monkey::getMonkey 失败,因为 thisMonkey = new Monkey() 返回“不允许抽象类类型“monkey”的对象”。我知道你不能实例化抽象类,但是我的猴子实现了两个抽象类(意味着它不是抽象的......对吗?)

这个问题的解决方案是什么?

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;
}

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森末i 2024-12-13 02:10:30

您没有显示足够的内容来准确地说,但先验的是,您的类 monkey
没有实现基类中的所有纯虚函数。具有未被重写的纯虚函数的类是抽象的。

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.

旧伤还要旧人安 2024-12-13 02:10:30

查找 anmialnpc 类中声明为纯虚拟的所有方法,并在 Monkey 类中为它们提供实现。它们是 Monkey 类的基类,看来您还没有实现它们的抽象接口。

纯虚拟类看起来像:

return_type methodName(params)=0;

您必须在派生类(monkey)中提供具有确切原型和实现的函数。当您有一个指向派生类之一的指针并调用该“纯虚拟”函数时,将调用此函数。即

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

会映射到:

monkey::methodName

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文