c ++重载运算符==

Jer*_*iah 0 c++ operator-overloading

我有一个课程如下

bool DistinctWord::operator==(const DistinctWord W) const
{
    return strWord == W.strWord;
}
bool DistinctWord::operator==(const DistinctWord& W) const 
{
    return strWord == W.strWord;
}
Run Code Online (Sandbox Code Playgroud)

我在我的程序中这样做

    DistinctWord* wordOne = new DistinctWord("Test");
    DistinctWord* wordTwo = new DistinctWord("Test");

    if(*wordOne == *wordTwo)
        cout << "true";
    else
        cout << "false";
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

错误C2678:二进制'==':找不到带有'DistinctWord'类型的左手操作数(或者没有可接受的转换)的运算符'可以'内置C++运算符==(DistinctWord*,DistinctWord*

)"

我可能只是不理解正确的重载方式.

对不起这个简单的问题.TIA

Eva*_*ran 5

编辑:

好的,我已经找到了你的问题.它是非参考版本的operator==.这使得operator==模棱两可.简单地删除它(正如我最初建议的那样)它会正常工作.


编辑:

为了响应您的编辑,您仍应删除第一个版本的" operator==无需复制有问题的对象",然后进行比较.第二个operator==看起来合理,应该工作.你有什么别的吗?


编辑:

使用g ++ 4.4.1,以下编译对我来说很好:

#include <iostream>

struct DistinctWord {
    DistinctWord(const std::string &s) : strWord(s){}

    bool operator==(const DistinctWord& W) const {
        return strWord == W.strWord;
    }

    std::string strWord;
};


int main() {
    DistinctWord* wordOne = new DistinctWord("Test");
    DistinctWord* wordTwo = new DistinctWord("Test");

    if(*wordOne == *wordTwo)
        std::cout << "true";
    else
        std::cout << "false";
}
Run Code Online (Sandbox Code Playgroud)

如果您仍然遇到问题,那么您没有显示所有相关代码......


首先,它的定义在哪里DistinctWord以及它与之相关Word

除此之外,你应该这样做:

bool Word::operator==(const Word& W) const {
     return strWord == W.strWord;
}
Run Code Online (Sandbox Code Playgroud)

然后删除operator==你现在拥有的两个.第一个是复制,然后比较哪个是愚蠢的,你的第二个是比较一个可修改的引用,总是返回true,这实际上没有任何用途.

这个应该工作正常.