1

我在以下 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"))??任何帮助表示赞赏。

4

4 回答 4

34

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

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

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

bool operator ==(const A &other) const
{
        return strcmp(a, other.a) == 0;
}
于 2009-12-07T13:46:53.667 回答
3
bool operator ==( const A &other)

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

于 2009-12-07T13:46:16.057 回答
2

在我看来,您希望在操作员中使用此功能:

strcmp(a, other.a) == 0

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

于 2009-12-07T13:47:49.020 回答
-1

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

bool operator==(const A& other) const

身体是一样的。

于 2009-12-07T13:47:58.193 回答