gpt4 book ai didi

具有类型的 C++ 多态性

转载 作者:行者123 更新时间:2023-11-30 01:51:51 25 4
gpt4 key购买 nike

我正在尝试创建一个节点,它有一个类型为 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()'

最佳答案

我相信您混淆了运行时多态性和编译时多态性。模板提供了后者。您的问题的一种可能解决方案是使 NodeBase 成为模板类:

template <class T>
class NodeBase {
public:
virtual T getData() = 0;
};

template <class T>
class Node : NodeBase<T> {
T data;
NodeBase *parent;

public:
Node(T);
void setData(T);
T getData(void);
void setParent(NodeBase<T> * const);
NodeBase<T> * getParent(void);
};

请注意,我让 getData 返回 T 而不是 T*。 (是否有返回指针的原因?)

关于具有类型的 C++ 多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25588415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com