如何重载 == 运算符以允许在多重比较中使用它?
我正在尝试重载 == 运算符来比较如下所示的对象。
class A
{
int a;
public:
A(int x) { a = x; }
bool operator==(const A& obRight)
{
if(a == obRight.a)
{
return true;
}
return false;
}
};
int main()
{
A ob(10), ob2(10), ob3(10);
if(ob == ob2) // This equality comparison compiles fine.
cout<<"Equal"<<endl;
if(ob == ob2 == ob3) //This line doesn't compile as overloaded
// == operator doesn't return object (returns bool)
cout<<"Equal"<<endl;
}
正如我上面所描述的,我无法在一行中进行多个对象比较
就像 if(ob == ob2 == ob3)
通过成员函数使用重载 == 运算符。
我应该使用友元函数重载吗?
I am trying to overload == operator to compare objects like below.
class A
{
int a;
public:
A(int x) { a = x; }
bool operator==(const A& obRight)
{
if(a == obRight.a)
{
return true;
}
return false;
}
};
int main()
{
A ob(10), ob2(10), ob3(10);
if(ob == ob2) // This equality comparison compiles fine.
cout<<"Equal"<<endl;
if(ob == ob2 == ob3) //This line doesn't compile as overloaded
// == operator doesn't return object (returns bool)
cout<<"Equal"<<endl;
}
As i described above, i am unable to do multiple object comparison in a single line
like if(ob == ob2 == ob3)
using overloaded == operator through member function.
Should i overload using friend function ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,你从根本上误解了你的操作。
想想类型。
你需要有
No. You fundamentally misunderstood your operation.
Think about the types.
You need to have
通常,您在实际代码中不应该这样做。
因为用法与其他人的期望完全不同。意外的事情是不直观的,并且不直观使得代码对于不熟悉代码库的人来说难以维护(或理解)。
但作为一项学术练习。
您想要的是让运算符 == 返回一个对象,这样如果在另一个测试中使用它,它将执行测试,但如果它只是留在布尔上下文中,那么它将自动转换为布尔值。
As a rule you SOULD NOT DO THIS in real code.
As the usage is completely different from what other people are expecting. Unexpected things are non-intuitive, and non-intuitive makes the code hard to maintain (or understand) for somebody that is not familiar with the code base.
But as an academic exercise.
What you want is to get the operator == to return an object so that if it is used in another test it will do the test but if it is just left in a boolean context then it will auto convert to bool.
您可以创建一个这样的函数
并使用它
You can create a function like this
and use it