已经好几天没有解决我的问题了……
我正在尝试搜索项目以对其进行修改。使用“列表”,我需要使operator ==重载,但我不明白我的错误。您能告诉我如何解决吗?
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
类型重载了运算符。没有重载的=
占用Nation
和string
。
两种解决方案:
您可以重载转换为字符串(不推荐),也可以创建一个采用字符串的构造函数。
[最佳解决方案是为getter
创建pays
方法,而只是要做il->getPays() == nomPays
。简洁明了。
您不必在类中重载运算符。原因如下:您已经使用std::list
。那很好。现在,再往前走一步,并放弃自己的algorithm,转而使用标准的std::find_if
。
std::find_if
可以使用您提供的比较functor搜索标准容器类。通常,该函子是带有重载std::find_if
的struct
(因此可以像函数一样使用其对象)。
我给你举个例子:
operator()
我还确保字符串由const&传递,这应该是至少在C ++ 11之前的字符串参数的默认值。我用&传递了#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!";
}
}
,这也更有可能是预期的行为(因为它不会创建不必要的副本)。
顺便说一下,您的liste
类很奇怪。它包含一个“国家”(付费)和一个“镇”(维尔)。这意味着在您的课堂设计中,一个国家包含一个国家和一个城镇。除了城市州以外,这没有意义;)
Edit:我忘记了实现细节。由于函子无法直接访问Nation
的pays
成员,请考虑为您的类提供成员函数,例如:
Nation
或将函子设为std::string GetPays() const
{
return pays;
}
的friend
。