【问题标题】:Problem with operator ==运算符问题==
【发布时间】:2010-12-24 00:32:19
【问题描述】:

我在以下 c++ 程序中使用 operator == 时遇到了一些问题。

#include < iostream>
using namespace std;

class A
{
    public:
        A(char *b)
        {
            a = b;
        }
        A(A &c)
        {
            a = c.a;
        }
        bool operator ==(A &other)
        {
            return strcmp(a, other.a);
        }
    private:
        char *a;
};


int main()
{
    A obj("test");
    A obj1("test1");

    if(obj1 == A("test1"))
    {
        cout<<"This is true"<<endl;
    }
}

if(obj1 == A("test1")) 行有什么问题??任何帮助表示赞赏。

【问题讨论】:

    标签: c++ operators equals-operator


    【解决方案1】:

    strcmp 当字符串相等时返回 0,所以你想要:

    return strcmp(a, other.a) == 0;
    

    您还应该使用 const 引用,就像 Cătălin Pitiş 在他的回答中所说的那样,因为这样您就可以将临时对象与运算符一起使用,并且您还应该使方法本身 const(因为它不会修改object) 正如 Andreas Brinck 在下面的 cmets 中所说。所以你的方法应该是:

    bool operator ==(const A &other) const
    {
            return strcmp(a, other.a) == 0;
    }
    

    【讨论】:

    • 函数也应该是常量:bool operator ==(const A &amp;other) const
    【解决方案2】:
    bool operator ==( const A &other)
    

    使用 const 引用,因此 if 语句中构造的临时对象可以用作 operator== 的参数。

    【讨论】:

    • 感谢您的快速回复!!我观察到的一件事是,为了让这个起作用,副本构造函数参数也应该设为 const。 A(const A &c)
    • 你能举例说明答案吗??
    • @Graeme Perrow:没错。 另外是strcmp 的问题,但是如果没有在此答案中进行更改,它甚至无法编译。
    • @Graeme:这是正确的答案。我引用了这个问题:“if(obj1 == A("test1")) line 有什么问题?”。 strcmp也有问题,但不是那个问题...
    • OP 期望看到“这是真的”作为输出 - 原始代码没有打印它。我将原始代码复制到一个文件中以验证这一点。 (@sth:编译成功。)我添加了const 行并重新构建它,它仍然没有打印任何内容,这意味着您的回答没有解决问题。如果我在 Mike Weller 的答案中更改了 strcmp,则无论是否添加了 const,输出都是正确的。
    【解决方案3】:

    在我看来您希望在您的运算符中使用这个:

    strcmp(a, other.a) == 0
    

    strcmp 在字符串匹配时返回 0,并返回一个数字,指示比较是否大于或小于其他情况。

    【讨论】:

      【解决方案4】:

      您的错误是您创建了一个即时值并将其作为引用传递给operator== 方法。但是您的错误在于您的运算符定义中应该是:

      bool operator==(const A& other) const

      身体是一样的。

      【讨论】:

      • 添加 const 内容绝对是个好主意,只需添加具有“主体相同”的 const 会导致与原始程序相同的错误行为。跨度>
      • 更正:在某些平台上,const 不仅仅是一个好主意,它是必需的。 Mike 的strcmp 更改仍然是正确行为所必需的。
      猜你喜欢
      • 2011-03-21
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多