我很难理解如何实现这一点。
这是我迄今为止尝试过的原型和实现(请注意,其中两个尝试已被注释掉 - 标记为(1)和(2)
//--- ADD PROTOTYPE OF ASSIGNMENT OPERATOR HERE
// (1) void operator=(const BST<DataType> & origList);
// (2) BST<DataType>& BST<DataType>::operator=(const BST& origList)
BST::operator=(const BST& origList);
目前每个结果都会出现以下错误:
home\visual studio 2010\projects\bst.h(139): error C4430: missing type specifier - int assumed.
以下是赋值运算符的实现:
//--- Definition of operator=
template <typename DataType>
BST<DataType>& BST<DataType>::operator=(const BST& origList)
{
if (this != &origList)
{
copyTree(origList.myRoot, myRoot);
destroy(myRoot);
}
return *this;
}
这是copyTree递归函数:
//--- Definition of copy constructor()
template <typename DataType>
BST<DataType>::BST(const BST<DataType> & origList)
{
copyTree(origList.myRoot, myRoot);
}
//--- Definition of copyTree()
template <typename DataType>
void BST<DataType>::copyTree(BinNodePointer origRoot, BinNodePointer & subtreeRoot)
{
if (origRoot == 0)
subtreeRoot = NULL;
else
{
subtreeRoot = new BinNode(origRoot->data);
copyTree(origRoot->left, subtreeRoot->left);
copyTree(origRoot->right, subtreeRoot->right);
//origRoot = new BinNode(subtreeRoot->data);
//copyTree(subtreeRoot->left, origRoot->left);
//copyTree(subtreeRoot->right, origRoot->right);
}
}
复制构造函数运行得很漂亮,但是赋值运算符我没能理解这里需要什么。非常感谢任何帮助!
P.S。您可能已经注意到我有“origList”,它应该被命名为“origTree”,但是我从之前为LinkedLists创建的构造函数中借用了它。
答案 0 :(得分:1)
这个
BST<DataType>& BST<DataType>::operator=(const BST& origList)
应该是
BST<DataType>& BST<DataType>::operator=(const BST<DataType>& origList)
在课程中使用以下声明
BST<DataType>& operator=(const BST<DataType>& origList)