【发布时间】:2020-05-05 17:10:52
【问题描述】:
我正在使用我之前定义的向量来实现二叉树。二叉树内部有一个结构节点,就像无法从我的节点函数访问在二叉树类中定义的向量一样。
这就是二叉树:
template <typename Data>
class BinaryTreeVec : public BinaryTree<Data>{
private:
protected:
using BinaryTree<Data>::size;
ulong height = 0;
public:
using typename BinaryTree<Data>::Node;
struct NodeVec : public Node{
private:
protected:
using Node::value;
ulong left;
ulong right;
ulong index;
ulong height;
bool isValid = false;
public:
friend class BinaryTreeVec<Data>;
....
bool HasLeftChild() const noexcept override; // Override Node member
bool HasRightChild() const noexcept override; // Override Node member
....
}
....
protected:
Vector<struct NodeVec> treeVec;
}
在我调用 HasLeftChild() 函数之前一切正常 错误:非静态数据成员“lasd::BinaryTreeVec::treeVec”的使用无效。 我的教授建议我使用引用是解决问题的最佳选择,因此尝试声明对 treeVec 的引用,以便我可以在 NodeVec 中使用它,但它完全没用。
template <typename Data>
bool BinaryTreeVec<Data>::NodeVec::HasLeftChild() const noexcept{
if( 2 * index + 1 < treeVec.Size())
return ( treeVec[2 * index + 1].flag == true );
return false;
}
每次我在此处的 HasLeftChild() 函数中使用 treeVec 时都会遇到编译器错误。
【问题讨论】:
-
'这完全没用' 可能你只是做错了,但我想我们永远不会知道。使用参考是一种解决方案,但还有其他解决方案。正常的方法是让您的节点类具有指向子节点的指针。我想你没有这样做是有原因的,因为它是最简单的选择。另一种选择是将树向量作为参数传递给 HasLeftChild。
-
如何通过参考解决?
-
好吧,将引用(我猜是树)放入您的 Node 类中,在 Node 构造函数中对其进行初始化,在 HasLeftChild 中使用它。
-
是否可以在 Node 中引用 treeVec?以便 Node 知道它所在的 Vector?
-
是的,这正是您的教授所建议的(我假设)。我的意思是我不认为这是特别出色的设计,但我想不出他还有什么意思。
标签: c++ compiler-errors static