【问题标题】:Problem implementing pure virtual class in C++在 C++ 中实现纯虚拟类的问题
【发布时间】: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 中有很多常用名称。

标签: c++ class


【解决方案1】:

typeid(NeighborTile *) != typeid(FloorTile *)。签名不同,因此即使 NeighborTile 继承自 FloorTile,它们也不会算作“相同”方法。

【讨论】:

    猜你喜欢
    • 2012-11-13
    • 2012-10-11
    • 1970-01-01
    • 2010-11-13
    • 2018-10-14
    • 2011-07-10
    • 1970-01-01
    • 2016-02-18
    • 2012-05-04
    相关资源
    最近更新 更多