所以这是具有左、右、父和数据的二叉搜索树的基类。
template<class Data>
class BSTNode
{
public:
/** Constructor. Initialize a BSTNode with the given Data item,
* no parent, and no children.
*/
BSTNode(const Data & d) : data(d)
{
left = right = parent = 0;
}
BSTNode<Data>* left;
BSTNode<Data>* right;
BSTNode<Data>* parent;
Data const data; // the const Data in this node.
/** Return the successor of this BSTNode in a BST, or 0 if none.
** PRECONDITION: this BSTNode is a node in a BST.
** POSTCONDITION: the BST is unchanged.
** RETURNS: the BSTNode that is the successor of this BSTNode,
** or 0 if there is none.
*/
BSTNode<Data>* successor()
{
BSTNode<Data>* cursor;
BSTNode<Data>* par;
cursor = this->right;
par = this->parent;
if (this->right != NULL)
{
while (cursor->left != NULL) {
cursor = cursor->left;
}
return cursor;
}
if ((this->right == NULL) && (this == par->left))
return this->parent;
if ((this->right == NULL) && (this == par->right))
{
do
{
cursor = par;
par = par->parent;
if (par == NULL)
{return cursor;}
} while(cursor != par->left);
return par;
}
if (this->right == NULL && this->parent == NULL)
return NULL;
return NULL;
}
};
子类是 RSTNode,它应该使用 BSTNode 的所有成员并在其之上添加一个优先级:
template<class Data>
class RSTNode: public BSTNode<Data>
{
public:
int priority;
RSTNode(Data const & d)
: BSTNode<Data>(d)
{
//call a random number generator to generate a random priority
priority = rand();
}
};
现在的问题是我不确定如何为 RSTNode 实现构造函数,因为它出于某种原因无法识别 BSTNode 的成员。我知道它应该识别它们,因为它应该继承这些信息。提供任何帮助。
最佳答案
好的,我在 Visual Studio 中编译了它...
template<class Data>
class BSTNode
{
public:
/** Constructor. Initialize a BSTNode with the given Data item,
* no parent, and no children.
*/
BSTNode(const Data & d) : data(d)
{
left = right = parent = 0;
}
BSTNode<Data>* left;
BSTNode<Data>* right;
BSTNode<Data>* parent;
Data const data; // the const Data in this node.
};
template<class Data>
class RSTNode : public BSTNode<Data>
{
public:
int priority;
RSTNode(Data const & d)
: priority(rand()),
BSTNode<Data>(d)
{
left = 0; //Accessible because public
right = 0;
parent = 0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
RSTNode<std::string> node(std::string("test"));
return 0;
}
已编译,因此没有访问问题。与上面的其他张贴者一样,在我看来,您要么没有发布问题的详细信息,要么没有理解一些基本的东西。
>现在的问题是我不确定如何为 RSTNode 实现构造函数,因为它>出于某种原因无法识别 BSTNode 的成员。我知道它应该识别 >them 因为它应该继承这些信息。提供任何帮助。
上面的代码实现了一个构造函数,或者如果你想专门设置左、右和父集,那么你需要:
BSTNode(const Data & d, BSTNode* l, BSTNode* r, BSTNode* p)
: data(d),
left(l),
right(r),
parent(p)
{
}
然后在 RSTNode 中使用它,或者为 RSTNode 使用一个类似的传递给那个......
RSTNode(Data const & d, BSTNode* l, BSTNode* r, BSTNode* p)
: priority(rand()),
BSTNode<Data>(d,l,r,p)
{
}
希望对您有所帮助,请注意您应该更喜欢初始化列表而不是直接访问构造函数中的成员。但是,如果您不能更改基类,那么您将需要...
更正错别字 - 数据 -> 数据
关于c++ - 构造函数C++的 super 与子类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13082676/