C2678 二进制"=="未找到采用左操作数类型的运算符

c2678 binary '==' no operator found which takes a left-hand operand of type

本文关键字:操作数 类型 运算符 二进制 C2678      更新时间:2023-10-16

好几天了,我一直在处理我的问题,但没有得到答案。。。

我试图搜索一个项目来修改它。对于"列表",我需要重载运算符==,但我不明白我的错误。你能告诉我如何解决这个问题吗?

class Nation{
private :
    short continent;
    unsigned int population, superficie;
    string pays, ville;
public :
list<Nation>    lireRemplir(list<Nation>liste, const char nomALire[]);
Nation(short continent, unsigned int population, unsigned int superficie, string pays, string ville) {
    ..... // ok
    }
Nation(){};
void modifierContinent(list<Nation> liste, string nomPays, short nouveauContinent);
bool operator == (Nation &); //?
};
bool Nation::operator == (Nation & autre) {
    return this->pays == autre.pays;
}
void modifierContinent(list<Nation> liste, string nomPays, short nouveauContinent)
{
    //Nation uneNation(0,0,0,nomPays,"");
    for (list<Nation>::iterator il = liste.begin(); il != liste.end(); il++)
    {
        if (*il == nomPays){ cout << "found!"; }    
    }
}
int main()
{
    list<Nation>liste;
    liste=lireRemplir(liste, "Nation.txt"); //hidden but working
    modifierContinent(liste, "FRANCE", 5);
}

此处:

if (*il == nomPays){ cout << "found!"; } 

nomPays是类型字符串,但是您重载了另一个Nation类型的运算符。不存在占用Nationstring的过载=

两种解决方案:

您可以重载到字符串的转换(不推荐),也可以创建一个接受字符串的构造函数。

最好的解决方案是为pays创建一个getter方法,只做il->getPays() == nomPays。清晰简洁。

您不必重载类中的运算符。原因如下:您已经使用了std::list。这很好。现在更进一步,放弃自制的算法,转而使用标准算法:std::find_if

std::find_if可以使用您提供的比较函数搜索标准容器类。通常,该函子是一个带有重载operator()struct(因此它的对象可以像函数一样使用)。

我给你举个例子:

#include <algorithm> // for std::find_if
// ...
struct CountryComparison
{
    CountryComparison(std::string const &country) : m_country(country) {}
    bool operator()(Nation const &nation) const
    {
        return nation.pays == m_country;
    }
    std::string m_country;
};
void modifierContinent(list<Nation> &liste, string const &nomPays, short nouveauContinent)
{
    list<Nation>::const_iterator find_iter = std::find_if(liste.begin(), liste.end(),
        CountryComparison(nomPays));
    if (find_iter != liste.end())
    {
        cout << "found!";
    }
}

我还确保字符串通过const&,这应该是至少在C++11之前的字符串参数的默认值。并且我通过CCD_ 14;,这也更有可能是预期行为(因为它不会产生不必要的副本)。

顺便说一句,你的Nation课很奇怪。它包含一个"国家"(pays)和一个"城镇"(ville)。这意味着在你的课堂设计中,一个国家由一个国家和一个城镇组成。这是没有道理的,也许除了城市州;)


编辑:我忘记了一个实现细节。由于函子不能直接访问Nationpays成员,请考虑为类提供一个成员函数,如:

std::string GetPays() const
{
    return pays;
}

或者使函子为Nationfriend

相关文章: