【问题标题】:Segmentation fault when trying to compare calling object with another object尝试将调用对象与另一个对象进行比较时出现分段错误
【发布时间】:2016-04-27 20:17:09
【问题描述】:

我有以下代码,我试图将这个对象与另一个对象进行比较。但是当我尝试运行时它给出了分段错误。在告诉我要进行哪些更改的同时,还告诉我为什么会引发分段错误

#include<iostream>
using namespace std;
class opo
{
    public:
    bool operator==(opo temp);
};
bool opo::operator==(opo temp)
{
    if(*this == temp)
    {
        cout<<"same\n";
        return true;
    }
    else
    {
        cout<<"diff\n";
        return false;
    }
}

int main()
{
    opo a1,a2;
    a1==a2;
    return 0;
}

【问题讨论】:

  • 有趣。 你怎么知道两个对象是否相等? -- 答案 -- 它们相等是因为它们相等。这就是你的代码所说的。
  • 哦,谢谢你的评论。真的帮助我理解问题并解决它

标签: c++ operator-overloading


【解决方案1】:

你有一个无限递归循环。

if(*this == temp)

调用bool operator==(opo temp),其中包含 if 语句,然后再次调用该函数,依此类推。这将导致程序耗尽资源最终导致堆栈溢出或段错误。

当您检查平等时,您需要检查成员。由于您的类是无状态的(无成员),因此任何两个对象都应该相等。

如果你有这样的班级成员

class Foo
{
public:
    int a, b;
};

然后我们会有一个比较对象,比如

bool Foo::operator ==(const Foo & rhs)
{
    return a == rhs.a && b == rhs.b;
    // or with std::tie
    return std::tie(a, b) == std::tie(rhs.a, rhs.b);
}

【讨论】:

    【解决方案2】:
    bool opo::operator==(opo temp)
    {
        if(*this == temp) // calls this->operator==(temp)
    

    这只是再次调用 same 函数,导致无限递归,最终导致堆栈溢出。

    你需要想出一些实际的方法来判断两个对象是否相同,然后这样做。

    顺便说一句,您的操作员的签名是奇怪。您正在强制复制右侧参数的临时副本(原始代码中的a2)。一个更正常的实现可能看起来像

    struct opo {
        int m_value = 0;
        bool operator== (opo const &) const;
    };
    
    bool opo::operator==(opo const &other) const {
        // actually compare something
        return m_value == other.m_value;
    }
    

    注意事项:

    1. 我们通过引用获取右侧参数,这意味着我们不会创建临时副本
    2. 我们通过 const 引用来获取它,这意味着我们保证不会更改它(为什么要在比较时更改某些内容?)
    3. 我们的运算符也被标记为 const,所以我们保证也不更改左侧
    4. 我添加了一个成员,所以我可以比较一下

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2023-03-12
      • 2013-11-15
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 2021-05-29
      相关资源
      最近更新 更多