hg_*_*git 0 c++ operator-overloading c++11 c++14
我是否必须提供两个不同版本的运算符==重载,以便无论表达式的LHS和RHS变体如何都可以运行.例如.
Class A {
...
bool operator==(int const& L, A const& R);
bool operator==(A const& L, int const& R);
...
};
Run Code Online (Sandbox Code Playgroud)
用于 -
A a;
int x = 8;
if( a == 5 || x == a){
...
}
Run Code Online (Sandbox Code Playgroud)
为什么需要这样做?不是L == R== R == L?
C++没有定义任何可交换或对称的运算符.因此,它无法自动翻译:
if( x == a){
Run Code Online (Sandbox Code Playgroud)
至
if( a == x){
Run Code Online (Sandbox Code Playgroud)
或相反亦然.
如果您希望编译器能够正确处理
if( x == a){
Run Code Online (Sandbox Code Playgroud)
你必须operator==用第一个对象的类型重载为int或int const&.