【问题标题】:C++ Invalid New Expression Of Abstract Class TypeC++ 无效的抽象类类型的新表达式
【发布时间】:2020-10-08 03:22:28
【问题描述】:

我在使用 c++ 时收到此错误。我尝试了其他解决方案,例如使用共享指针,但无济于事。这是我的代码:

Main.cpp:

int main() {
    game_init();
    cout << items.at(0).name << endl; 
    while(true) game_tick();
    return 0;
}

项目.h:

#ifndef ITEM_H
#define ITEM_H
#include "../Rooms/Room.h"
#include <string>
#include <vector>
#include <memory>
using namespace std;

class Item {
    public :
        Room location;
        string name, desc;
        //Item(string, string, Room);
        virtual void use() = 0; 
        
};
vector <Item> items;

/*
Item::Item(string in_name, string in_desc, Room in_location) {
    name = in_name;
    desc = in_desc;
    location = in_location;
    
}*/
#endif

Items.h:

#ifndef ITEMS_H
#define ITEMS_H
#include "OldKey.h"

#include <memory>
#include <vector>

vector <shared_ptr<Item>> all_items;
OldKey   old_key;

void items_init() {
    items.push_back(old_key);
}
#endif

错误是抽象类类型“项目”的无效新表达式。希望我能解决这个问题,请记住我是 C++ 新手,所以请尝试简单地解释解决方案或解决方法,谢谢。

【问题讨论】:

  • 我认为这将有助于您理解抽象类:Why can't we create an instance of an abstract class?
  • 我找到了删除错误消息的方法。在项目类中,我定义了子类没有定义它的用途。但这意味着如果我要使用命令 items.at(anyindex).use(),它只会给出预定义的函数。我不知道该怎么做,希望得到帮助。

标签: c++


【解决方案1】:

您正在尝试使用纯虚函数 (use) 实例化一个类 (Item)。这是不允许的。要解决此问题,您可以

  • 创建一个实现use 函数的子类,然后实例化该子类而不是Item
  • 使函数虚拟而不是纯虚拟,即删除= 0,然后在Item 类中提供默认实现。然后,子类可以通过重写该函数来提供自己的 use 实现。

请注意,您对vector&lt;Item&gt; items 的定义看起来很可疑。如果您尝试在此向量中存储Item 的子类,那么它将被转换为Item 的实例,并且子类的所有信息都将丢失。例如,您可能希望将其更改为指针向量。

【讨论】:

  • 我之前做了后一种解决方法,但是当我调用 use 时,我得到的是父类方法而不是被覆盖的方法。要解决这个问题,我只需将 vector items 更改为 vector items
  • 好的,我找到了如何使用指针来解决它。感谢您的解释。
猜你喜欢
  • 2014-07-12
  • 1970-01-01
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
相关资源
最近更新 更多