我在以下 C++ 程序中使用运算符 == 时遇到一些问题。
#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"))
行有什么问题??感谢您的帮助。
最佳答案
strcmp
当字符串相等时返回 0,所以你想要:
return strcmp(a, other.a) == 0;
您还应该使用 const
引用,就像 Cătălin Pitiş 在他的回答中所说的那样,因为这样您就可以将临时对象与运算符一起使用,并且您还应该使方法本身成为 const
(因为它不修改对象)正如 Andreas Brinck 在下面的评论中所说。所以你的方法应该是:
bool operator ==(const A &other) const
{
return strcmp(a, other.a) == 0;
}
关于c++ - 运算符问题 ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1860065/