运算符问题==

CPP*_*Dev 1 c++ operators equals-operator

我在以下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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*ler 34

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

return strcmp(a, other.a) == 0;
Run Code Online (Sandbox Code Playgroud)

您还应该使用const像CătălinPitiş这样的引用在他的回答中说,因为那时你可以使用临时对象与操作符,你也应该自己创建方法const(因为它不会修改对象),正如Andreas Brinck在评论中所说的那样下面.所以你的方法应该是:

bool operator ==(const A &other) const
{
        return strcmp(a, other.a) == 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 函数也应该是const:`bool operator ==(const A&other)const` (2认同)