在C ++中,运算符可以重载。如果我有两个类A
和B
,例如我可以在类operator ==
中重载A
以与B
的实例进行比较:
class A {
// Some attributes, methods
public:
bool operator ==(const B &b) {
// Implementation of operator ==
}
}
然后我可以运行如下代码:
A a;
B b;
if(a == b) {
// Some code
}
但是,如果我编写b == a
,编译器将在B类中查找bool operator ==(const A &a)
。如果找不到,C ++规范化中是否存在默认行为?编译器,无论它是什么,退出失败或运行bool operator ==(const B &b)
而不是?
甚至更好,如果它没有在operator < ()
类中找到B
,它会在operator >=()
类中尝试A
吗?
不,它也不会这样做。重载运算符没有什么特别之处;它们只是重载函数,具有滑稽的语法。所以上面代码中的a == b
只不过是对a.operator==(const B&)
的调用。
当然,b == a
失败的原因是没有b.operator==(const A&)
(同样,没有全球运营商)。
处理这个问题的通常方法是拥有一个全球性的operator==
而不是一个成员:bool operator==(const A&, const B&)
,以及另一个全球性的operator==
:bool operator==(const B&, const A&)
;如果比较实际上是对称的,那么第二个可以通过调用第一个来实现:bool operator==(const B& b, const A& a) { return a == b; }
。
同样的原则也适用于operator<
:它没有其他方式,如果你想要一个,你必须写它。
(小字:请忽略 - 有std::relops
(拼写纠正想要改变“重新安置”到“复发”),这将提供这些变体;不要使用它;它太过于无形。)