C++重载运算符==

Pet*_*trS 1 c++ operator-overloading

我创建了一个类Location.这个类是类City和的父类Village.这Location门课是抽象的.我创建了一个vector<Location*> locations包含城市和村庄的地方.Location包含一个名字.如果两个位置具有相同的名称,则表示它们是相同的.我已经超负荷运营商==Location.

bool operator==(const Location& lhs) const
{
    return (this->mName.compare(lhs.mName) == 0);
}
Run Code Online (Sandbox Code Playgroud)

如果我想添加一些位置vector,我首先检查这个位置是否不存在.我用这个函数:

bool checkLocation(Location* l) {
    return find(locations.begin(), locations.end(), l) != locations.end();
}
Run Code Online (Sandbox Code Playgroud)

例如,如果我想在其中添加一些城市vector,则上述方法仍会返回false,这意味着Location不存在.但是在这个vector城市有一个同名的城市.你能告诉我,问题出在哪里?谢谢.

Naw*_*waz 7

由于向量存储指针,因此std::find将比较指针,这些指针不会调用Location::operator==()来比较元素.

你需要std::find_if和lambda一起使用:

return std::find_if(locations.begin(), 
                    locations.end(), 
                    [l](Location  const *x) {
                         return *l == *x;      //invoke operator=
                     }) != locations.end();
Run Code Online (Sandbox Code Playgroud)

lambda取消引用指针,然后使用==调用Location::operator=.

如果位置对象不是很大,我会建议您使用std::vector<Location>而不是std::vector<Location*>.如果您使用std::vector<Location>,那么您可以使用std::find,代码将被简化.

即使位置对象很大,最好使用智能指针而不是原始指针.

希望有所帮助.