C++ 如何重载==运算符以允许在多次比较中使用它?
我试图重载==运算符来比较下面这样的对象C++ 如何重载==运算符以允许在多次比较中使用它?,c++,operator-overloading,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
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;
}
A类
{
INTA;
公众:
A(intx){A=x;}
布尔运算符==(常量A和对象右侧)
{
if(a==obRight.a)
{
返回true;
}
返回false;
}
};
int main()
{
ob(10)、ob2(10)、ob3(10);
if(ob==ob2)//此等式比较编译良好。
不能,你根本误解了你的操作
if (ob == ob2 == ob3) =
if (ob == (ob2 == ob3)
想想这些类型
if (A == (A == A))
if (A == bool) // Oh dear, no == operator for bool!
你需要有
if ((ob == ob2) && (ob == ob3))
if ((A == A) && (A == A))
if (bool && bool) // fine
通常情况下,您不应该在实际代码中执行此操作。
因为它的用法与其他人所期望的完全不同。意外的事情是非直观的,并且非直观性使得不熟悉代码库的人很难维护(或理解)代码
但作为一种学术活动
您想要的是让运算符==返回一个对象,这样,如果在另一个测试中使用它,它将执行该测试,但如果它只是留在布尔上下文中,那么它将自动转换为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;
}
#包括
使用名称空间std;
模板
课堂测试
{
公众:
测试(T常量和v、布尔值)
:值(v)
,州(s)
{}
测试运算符==(T常量和rhs)常量
{
返回测试(值、状态和值==rhs);
}
运算符bool()常量
{
返回状态;
}
私人:
T常数&值;
布尔州;
};
甲级
{
INTA;
公众:
A(intx){A=x;}
测试运算符==(常量A和对象右侧)常量
{
返回测试(*this,a==obRight.a);
}
};
int main()
{
ob(10)、ob2(10)、ob3(14);
if(ob==ob2)//此等式比较编译良好。
cout您可以创建这样的函数
#include<stdarg.h>
template<class T>
bool equals(size_t num, T val,...)
{
va_list arguments;
va_start(arguments,num);
for(size_t i = 0; i<num; ++i)
if(val != va_arg(arguments, int))
{
va_end ( arguments );
return false;
}
va_end ( arguments );
return true;
}
如果(ob==ob2&&ob==ob3)
,为什么不做?作为旁注,你应该让操作符成为一个const
方法。作为一个改进的旁注,你应该让操作符成为一个朋友函数。(或者如果有一个访问器,只是一个普通的免费函数。)总是喜欢非朋友的非成员函数。呵呵,好的:)但我认为“这行代码无法编译"是误导性的——它编译并运行良好!哎哟。我的错误。观点是一样的。如果T
是非POD类类型,那么当您通过…
参数传递该类型的值时,行为是未定义的。在这种情况下,它恰好是正常的,但一般来说并不正常。+1,尽管根据标准5.2.2/7-8,只有基本属性pes和POD类可以作为参数传递给…
(这意味着没有包含虚拟函数、构造函数或析构函数的类)
if(equals(3,ob1,ob2,ob3))
//do some stuff here