1

我在编译期间两次收到上述错误消息。其他一切正常,即没有其他编译时错误。这是一个简单的二叉树程序,错误来自的函数是交换或镜像函数,旨在简单地交换所有子树。这是功能

template <class dataType>
void swapSubTrees ( BinaryTree <dataType> * bt )
{
    if(bt == NULL)
    {
        //do nothing  
    }
    else
    {  
        swapSubTrees(bt->left());
        swapSubTrees(bt->right());
        BinaryTree <int> *temp;
        temp = bt->left();
        bt->left() = bt->right();
        bt->right() = temp;
   }
}

这是我的主要函数调用(这是我得到两个非左值错误的地方

swapSubTrees (b1);

b1 是从类 BinaryTree 实例化的对象,它位于树的顶部。有相应的对象 b2、b3、b4 和 b5 是树的其他节点,显然来自我遗漏的代码。无论如何,我似乎无法找到我出错的地方,它可能是什么?任何帮助都会非常感谢!左边的函数看起来像

Template <class dataType>
BinaryTree <dataType> * BinaryTree<dataType> :: left()
{
    return leftTree;
}
4

4 回答 4

4

我猜测给出错误的行是:

bt->left() = bt->right();
bt->right() = temp;

?

您不能将这样的函数调用用作表达式的左侧。


将此方法添加到 BinaryTree 模板类:

template<class dataType>
void BinaryTree<dataType>::swapChildren()
{
    BinaryTree *tmp = leftTree;
    leftTree = rightTree;
    rightTree = tmp;

    if (leftTree)
        leftTree->swapChildren();
    if (rightTree)
        rightTree->swapChildren();
}

然后将您的自由功能更改为:

template <class dataType>
void swapSubTrees ( BinaryTree <dataType> * bt )
{
    if(bt != NULL)
        bt->swapChildren();
}
于 2013-10-30T10:14:37.953 回答
1

添加

void setLeft( BinaryTree <dataType> * other );

void setRight( BinaryTree <dataType> * other );

对于您的 BinaryTree 类,假设它们尚不存在(我将把它们的实现留给您!)

然后将错误行更改为

bt->setLeft( bt->right() );
bt->setRight( temp );
于 2013-10-30T10:30:18.113 回答
0

The problem here is that you are trying to assign a value to an rvalue.

Essentially, the cause is that the value returned by left and right is a temporary object. You're returning a copy of the pointer, and this copy cannot be assigned to.

The way to get this to compile is to change the left and right functions to return a reference to your pointer, which can be assigned to. This is done as follows:

Template <class dataType>
BinaryTree <dataType>*& BinaryTree<dataType> :: left()
{
    return leftTree;
}

(And similarly for right)

Note the ampersand (&) after the asterisk (*). This means the returned value is a reference. This is called returning by reference, rather than returning by value.

Now, this would cause the code to compile. But you really should ask yourself if this is what you want. Do you want someone from outside to be allowed to change what leftTree points to inside the BinaryTree?

A better option would likely be to add a setter function for these two, and call these instead.

于 2013-10-30T10:27:55.050 回答
-1

如果您将函数 left() 和 right() 重写为返回对指针的引用,那么就不会有问题。:)

于 2013-10-30T10:18:29.307 回答