【发布时间】:2014-08-31 02:17:22
【问题描述】:
我正在尝试拥有一个具有 T 类型变量的节点,T data; 以及存储指向其父节点 NodeBase *parent; 的指针。
类如下所示:
class Node: public NodeBase {
T data;
NodeBase *parent;
public:
Node(T);
void setData(T);
T * getData(void);
void setParent(NodeBase * const);
NodeBase * getParent(void);
};
class NodeBase {
};
我以为我可以在NodeBase中放一个纯虚函数,但是你必须指定返回类型,因为NodeBase没有类型我不能指定virtual T * getData(void) = 0;
我遇到问题的具体案例:
Node<char> n1 = Node('A');
Node<int> n2 = Node(63);
n1.setParent(&n2);
NodeBase *pNode = n1.getParent();
pNode->getData(); // Error: BaseNode has no member 'getData()'
【问题讨论】:
-
getData 必须是 nodebase 的虚拟成员函数 - 更重要的是它必须具有已知类型,以便对
NodeBase* p; p->getData();的每次调用都将返回相同的类型 -
你能把
NodeBase做成一个模板类吗? -
另外,
NodeBase的目的是什么?你会有多个实现吗? -
@Code-Apprentice 即奇怪地重复出现的模板模式?这是一个很好/惯用的解决方案,但 OP 需要了解不同类型的两个节点不能被视为具有相同的基本类型。
-
@user3125280 OIC...OP 想要
Node<char>和Node<int>的通用基类。
标签: c++ templates inheritance polymorphism virtual