"Allocating an object of abstract class type"错误,尽管所有函数都有实现

"Allocating an object of abstract class type" error although all functions have implementations

本文关键字:实现 函数 错误 an Allocating object of class abstract type      更新时间:2023-10-16

我知道关于这个错误的问题已经被反复问过,但是以前的答案似乎都没有解决我的问题。

我有一个纯抽象类ITile

class ITile {
public:
    virtual ~ITile() {}
    virtual void display() = 0;
    virtual bool isWalkable() = 0;
    virtual bool isGoal() = 0;
};

还有三个子类都实现了这些函数,如下所示:

地板.h

#include "ITile.h"
class Floor : public ITile {
public:
    Floor();
    virtual ~Floor();
    virtual void display() override;
    virtual bool isWalkable() override;
    virtual bool isGoal() override;
};

地板.cpp

#include "Floor.h"
#include <iostream>
using namespace std;
Floor::Floor() {}
Floor::~Floor() {}
void Floor::display() {
   cout << " ";
}
bool Floor::isWalkable() {
    return true;
}
bool Floor::isGoal() {
    return false;
}

尝试编译整个项目时,我得到以下输出:

g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/main.d" -MT"src/main.d" -o "src/main.o" "../src/main.cpp"
In file included from ../src/main.cpp:1:
In file included from ../src/board.h:1:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/vector:265:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__bit_reference:15:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/algorithm:627:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/memory:1641:31: error: allocating an object of abstract class type 'ITile'
        ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
[...]

。然后是一堆笔记。但问题是,我想,上面最后一行的错误。

那么,这些algorithmmemory文件等到底是什么呢?如何摆脱此错误?

我正在使用 Eclipse Luna 和 Mac OS X (Mavericks) 上的 C/C++ 插件和开发人员命令行工具。更多信息很乐意应要求提供。

提前感谢!

你不能声明std::vector<ITile>,因为ITile不能存在。

为了在容器中使用多态性,您需要存储指针。这些指针将指向动态分配的 FloorWallCeiling 等类型的对象,无论您拥有什么其他对象。

考虑一个std::vector<std::unique_ptr<ITile>>

ITile是一个

抽象类。

对于 C++11 之前的编译器,无法创建 std::vector<ITile>std::vector只能与 CopyConstructable 和 CopyAssignable 的类型一起使用。抽象类既不是 CopyConstructable 也不是 CopyAssignable。

如果您使用的是 C++11 或更高版本的编译器,则类型不需要为 CopyConstructible 和 CopyAssignable 来构造std::vector。其他成员职能可能会施加这些要求。如果您的编译器不严格合规,则它将无法为此类类型构造std::vector

更多信息:

http://en.cppreference.com/w/cpp/container/vectorhttp://en.cppreference.com/w/cpp/concept/CopyConstructiblehttp://en.cppreference.com/w/cpp/concept/CopyAssignable