"Allocating an object of abstract class type"错误,尽管所有函数都有实现
"Allocating an object of abstract class type" error although all functions have implementations
我知道关于这个错误的问题已经被反复问过,但是以前的答案似乎都没有解决我的问题。
我有一个纯抽象类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)...);
[...]
。然后是一堆笔记。但问题是,我想,上面最后一行的错误。
那么,这些algorithm
、memory
文件等到底是什么呢?如何摆脱此错误?
我正在使用 Eclipse Luna 和 Mac OS X (Mavericks) 上的 C/C++ 插件和开发人员命令行工具。更多信息很乐意应要求提供。
提前感谢!
你不能声明std::vector<ITile>
,因为ITile
不能存在。
为了在容器中使用多态性,您需要存储指针。这些指针将指向动态分配的 Floor
、Wall
、Ceiling
等类型的对象,无论您拥有什么其他对象。
考虑一个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
- 在命名空间内部还是外部实现 c++ 函数?
- 如何在C++中实现函数(f)(x)(y, z)(g)(r)
- 如何在C++中实现函数上的二叉搜索?
- 键按下事件错误 Qt 实现函数时
- 在子类之外实现函数导致未知错误
- 通过模板滥用实现函数式C++
- C++,实现函数"int next(std::string param)"时出现奇怪的编译器错误
- 我正在尝试创建自己的 strcat() 函数,而不是使用库实现函数<cstring>
- 如果未实现函数,则在链接时启用错误
- 用函数参数实现c++函数指针
- 如何在Android SDK中调用和实现C++函数
- 在 C++ RCPP 中实现 R 函数
- 实现函数模板填充多维对象
- 类的层次结构,试图在基本级别实现函数
- 用c++实现函数对象的自动检测类型
- 用shared_ptrs实现函数模板的C++实例化
- 在类中实现函数导致错误:成员引用基类型'ifstream (string)'不是结构或联合
- 用c++实现S函数.生成错误
- 引用可以用于实现函数重写吗
- 如何在c++中实现函数超时