bjs*_*123 2 c++ operator-overloading
我试图重载==运算符来比较下面的对象.
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;
}
Run Code Online (Sandbox Code Playgroud)
如上所述,我无法在单行中进行多个对象比较,
例如 if(ob == ob2 == ob3)通过成员函数使用重载==运算符.
我应该使用友方功能超载吗?
Pup*_*ppy 11
不,你从根本上误解了你的操作.
if (ob == ob2 == ob3) =
if (ob == (ob2 == ob3)
Run Code Online (Sandbox Code Playgroud)
想想类型.
if (A == (A == A))
if (A == bool) // Oh dear, no == operator for bool!
Run Code Online (Sandbox Code Playgroud)
你需要拥有
if ((ob == ob2) && (ob == ob3))
if ((A == A) && (A == A))
if (bool && bool) // fine
Run Code Online (Sandbox Code Playgroud)
Mar*_*ork 11
作为一项规则,你不应该在实际代码中这样做.
由于使用方式与其他人的期望完全不同.意外的事情是非直观的,并且非直观性使得代码难以维护(或理解)不熟悉代码库的人.
但作为一项学术活动.
你想要的是让operator ==返回一个对象,这样如果它在另一个测试中使用它将进行测试,但如果它只是留在布尔上下文中,那么它将自动转换为bool.
#include <iostream>
using namespace std;
template<typename T>
class Test
{
public:
Test(T const& v, bool s)
:value(v)
,state(s)
{}
Test operator==(T const& rhs) const
{
return Test<T>(value, state && value == rhs);
}
operator bool() const
{
return state;
}
private:
T const& value;
bool state;
};
class A
{
int a;
public:
A(int x) { a = x; }
Test<A> operator==(const A& obRight) const
{
return Test<A>(*this, a == obRight.a);
}
};
int main()
{
A ob(10), ob2(10), ob3(14);
if(ob == ob2) // This equality comparison compiles fine.
cout<<"Equal"<<endl;
if(ob == ob2 == ob3)
cout<<"Equal"<<endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1955 次 |
| 最近记录: |