【问题标题】:Overriding == operator in C++ [duplicate]在 C++ 中覆盖 == 运算符 [重复]
【发布时间】:2019-07-01 04:04:15
【问题描述】:

我试图覆盖一个类的 == 运算符,但是比较似乎以某种方式失败。当我编写与名为 eq(例如)的函数相同的函数时,不会出现问题。

class geo
{
    ...
        bool operator==(geo const& other)
        {
            if(_id != other._id) return false;
            if(!(name == other.name))return false; 
            if(is_primary!=other.is_primary)return false;
            for(int i = 0; i<6;i++){
                if(position[i]!=other.position[i])
                    return false;
            }
            return true;
        }
   ....
    private:
        int _id, is_primary;
        vector position;
        string name;

}

在主函数中: ...

geo* i= new geo(2.1, 2.82, 1, 0, 0, 180, 0, "Patient-1",1);
geo* j= new geo(2.1, 2.82, 1, 0, 0, 180, 0, "Patient-1",1);
if(i==j)
    std::cout<<"they are equal\n";

但是当我运行它时,它说 i 和 j 是不同的。知道我在哪里做错了吗?

编辑: 谢谢你们在 cmets 的家伙。我刚刚解决了它; 上面显示的代码工作得很好。当然,如果我试图简化代码以使此处粘贴可读的内容。所以我正在更新上面的代码,把它变成一个问题,这样未来的读者可能会看到比我更好的解决方案,并且我可以学到更多。

【问题讨论】:

  • 请提供构造函数声明,对于 geo ?并且“向量位置”在语法上是有效的??
  • “知道我哪里做错了吗?” - 是的,你没有显示的代码有问题。
  • 通过在每个 return false 语句上放置断点来调试它并检查返回 false 的位置
  • 你来自 Java 吗?您几乎不应该在 C++ 中使用指针和 new
  • 如果你需要拥有/管理指针,你应该使用智能指针。原始指针不是管理的,不应该用new 初始化,但总是用现有对象的地址初始化。通常你只使用对象。 geo i(2.1, 2.82, 1, 0, 0, 180, 0, "Patient-1",1);.

标签: c++ overriding comparison-operators


【解决方案1】:

通过执行i == j,您将比较两个指向geo 的指针,而不是它们指向的对象。由于指针明显不同,因此您会得到这样的结果。

要实际比较对象,您需要取消引用指针:

if (*i == *j) `

【讨论】:

    【解决方案2】:

    在我看来,您的地理类的比较运算符似乎是其成员的字典比较。

    您可能有兴趣知道可以使用tuple 来统一所有比较运算符,方法是按适当顺序构建成员的std::tie

    例子:

    #include <string>
    #include <vector>
    #include <tuple>
    #include <iostream>
    
    class geo
    {
    public:
        template<class...Args>
        geo(Args&&...);
    
    private:
        auto as_tuple() const { 
            // note: mentioned in lexographical order
            return std::tie(_id, name, is_primary, position); 
        }
    
        friend auto operator ==(geo const& l, geo const& r) -> bool
        {
            return l.as_tuple() == r.as_tuple();
        }
    
        friend auto operator <(geo const& l, geo const& r) -> bool
        {
            return l.as_tuple() < r.as_tuple();
        }
    
    private:
        int _id, is_primary;
        std::vector<int> position;
        std::string name;
    };
    
    
    int main()
    {
        geo i= geo(2.1, 2.82, 1, 0, 0, 180, 0, "Patient-1",1);
        geo j= geo(2.1, 2.82, 1, 0, 0, 180, 0, "Patient-1",1);
    
        if(i==j) {
            std::cout<<"they are equal\n";
        }
    
        if(i < j) {
            std::cout<<"i is less\n";
        }
    }
    

    【讨论】: