运算符 == 的问题
我在以下 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"))
行有什么问题?任何帮助表示赞赏。
I am facing some problem with use of operator == in the following c++ program.
#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;
}
}
What's wrong with if(obj1 == A("test1"))
line ?? Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当字符串相等时,
strcmp
返回 0,所以你想要:你还应该使用
const
引用,就像 Cătălin Pitiş 在他的回答中所说,因为这样你就可以使用临时对象运算符,并且您还应该将方法本身设置为 const(因为它不会修改对象),正如 Andreas Brinck 在下面的评论中所说。所以你的方法应该是:strcmp
returns 0 when the strings are equal, so you want:You should also use a
const
reference like Cătălin Pitiș says in his answer, because then you can use temporary objects with the operator, and you should also make the method itselfconst
(since it doesn't modify the object) as Andreas Brinck says in the comments below. So your method should be:使用const引用,因此在if语句中构造的临时对象可以用作operator==的参数。
Use const reference, so a temporary object that is constructed in if statement can be used as parameter for operator==.
在我看来,您希望在运算符中使用此操作:
当字符串匹配时,
strcmp
返回 0,并指示比较是否大于或小于其他情况的数字。It looks to me like you want this in your operator:
strcmp
returns 0 when strings match, and a number indicating whether the comparison is greater or less than otherwise.您的错误是您创建了一个即时值并将其作为引用传递给
operator==
方法。但是您的错误在于您的运算符定义中应该是:bool operator==(const A& other) const
主体相同。
Your error is that you create an instant value and pass it as reference to the
operator==
method. But your error is in your operator definition that should be:bool operator==(const A& other) const
the body being the same.