c++ - 比较同一类的 2 个对象(覆盖 == 运算符)c++

标签 c++ class overriding operator-keyword

我是 C++ 的新手(来自 Java 和 C#),我正在尝试覆盖我的一个类中的 == 运算符,这样我就可以查看是否有 2 个对给定值具有相同值的对象属性(property)。我一直在谷歌搜索并尝试做一些有用的东西。我需要的是 == 运算符在 2 个对象具有相同的 _name 文本时返回 TRUE。

这是头文件:

//CCity.h -- city class interface
#ifndef CCity_H
#define CCity_H

#include <string>

class CCity
{
friend bool operator ==(CCity& a,  CCity& b)
{
    bool rVal = false;
    if (!(a._name.compare(b._name)))
        rVal = true;
    return rVal;
}
private:
    std::string _name;
    double _x; //need high precision for coordinates.
    double _y;
public:
    CCity (std::string, double, double); //Constructor
    ~CCity (); //Destructor
    std::string GetName();
    double GetLongitude();    
    double GetLatitude();
    std::string ToString();
};
#endif

在我的 main() 方法中:

    CCity *cit1 = new CCity("bob", 1, 1);
    CCity *cit2 = new CCity("bob", 2, 2);
    cout<< "Comparing 2 cities:\n";
    if (&cit1 == &cit2)
        cout<< "They are the same \n";
    else
        cout << "They are different \n";
    delete cit1;
    delete cit2;

问题是我在 friend bool operator == block 中的代码永远不会执行。我觉得我在声明该运算符的方式或使用它的方式上做错了。

最佳答案

& 获取地址(你正在比较指针),当你真的想使用 * 取消引用时:

if (*cit1 == *cit2)
    cout<< "They are the same \n";

无论如何,这里绝对没有使用指针的意义,更不用说愚蠢的指针了。

这是没有它们的样子(正确的方式):

CCity cit1("bob", 1, 1);
CCity cit2("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (cit1 == cit2)
    cout<< "They are the same \n";
else
    cout << "They are different \n";

此外,正如 WhozCraig 所提到的,请考虑为您的 operator== 函数使用 const-ref 参数,因为它不应修改参数。

关于c++ - 比较同一类的 2 个对象(覆盖 == 运算符)c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14680190/

相关文章:

java - 调用重写的 super 方法会导致无限递归

c++ - 为什么要写两个 () 运算符

PHP:如何在类中创建动态变量

C++成员函数定义类前缀快捷方式(也是模板)

c++ - 创建一个类来表示商店的库存是否有意义?

c++覆盖数组类的>>运算符

c++ - 根据条件从函数模板返回不同的类型

c++ - 尽管需要函数指针,但使用函数对象

c++ - 子表达式求值顺序的不可预测性

Java匿名子类和常规(非匿名)子类的区别