重载operator =时出错

时间:2014-10-27 16:17:18

标签: c++ operator-overloading

我构建了一个名为layerOneTree的redBlack树,现在我想为它重载operator =但是我不知道语法。

const layerOneTree& operator =(const layerOneTree &rhs); //in layerOneTree.h

实施:

layerOneTree& layerOneTree::operator= (const layerOneTree &rhs)//ERROR
{

if (this != &rhs) // if not self assignment
{
    reclaimMemory(m_root->rChildPtr); // clear its memory
    m_root->rChildPtr = theLeaf;
    m_root->rChildPtr = clone(rhs.m_root->rChildPtr);
}

return *this; // return current tree object
}

我知道layerOneTree* layerOneTree::operator=存在问题,但我不知道如何修复它。

编辑:当我在const layerOneTree& operator =(const layerOneTree &rhs);中省略const时一切正常,但我正在尝试编写像this这样的代码。如第43行所示,定义是const。为什么代码有效而我的代码没有?

1 个答案:

答案 0 :(得分:1)

成员函数的定义和声明必须匹配。解决方案是使两者都返回相同的类型变量:

const layerOneTree& operator =(const layerOneTree &rhs); //in layerOneTree.h


const layerOneTree& layerOneTree::operator= (const layerOneTree &rhs)
{// Code
}

或:

layerOneTree& operator =(const layerOneTree &rhs); //in layerOneTree.h


layerOneTree& layerOneTree::operator= (const layerOneTree &rhs)
{// Code
}

我更喜欢第二种形式,因为它更简单易懂。

两者之间的行为差​​异可以在这里找到:Overloading operators : const vs non-const return type : any difference of performance?