【发布时间】:2011-04-17 07:03:44
【问题描述】:
我有以下课程:
#include <string>
#include <stack>
#include <queue>
#include "map.h"
using namespace std;
#ifndef CONTAINER_H_
#define CONTAINER_H_
struct PathContainer {
int x, y;
string path;
};
class Container {
public:
virtual void AddTile(string, FloorTile *) = 0;
virtual void ClearContainer() = 0;
virtual PathContainer *NextTile() = 0;
};
class StackImpl : public Container {
private:
stack<PathContainer> cntr;
public:
StackImpl();
void AddTile(string, NeighborTile *);
void ClearContainer();
PathContainer *NextTile();
};
class QueueImpl : public Container {
private:
queue<PathContainer> cntr;
public:
QueueImpl();
void AddTile(string, NeighborTile *);
void ClearContainer();
PathContainer *NextTile();
};
#endif
当我尝试像这样创建 StackImpl 或 QueueImpl 对象时:
Container *cntr;
cntr = new StackImpl();
或
Container *cntr;
cntr = new QueueImpl();
编译时出现以下错误:
escape.cpp:在函数“int main(int, char**)”中: escape.cpp:26:错误:无法分配抽象类型“StackImpl”的对象 container.h:23: 注意:因为以下虚函数在‘StackImpl’中是纯函数: container.h:18:注意:虚拟 void Container::AddTile(std::string, FloorTile*)
有什么想法吗?
【问题讨论】:
-
还要注意,你的基类几乎肯定应该有一个虚拟析构函数(不要让它成为纯虚拟的,只是虚拟的)。
-
永远不要在头文件中放置
using namespace std;- 或任何using namespace声明。您将在包含您的标头的每个源文件上强加该声明,因此这被认为是一种非常糟糕的做法。 -
@Praetorian:原则上我同意(所以我+1 你,好先生),但至少
std是,嗯,std。在全局使用的所有命名空间中,它可能是最不邪恶的。 :) -
@Jonathan:我实际上认为它是最邪恶的,因为它是如此广泛,而且命名空间
std中有很多常用名称。