#include <iostream>
#include <fstream>
using namespace std;
class binaryOperators
{
public:
int i;
binaryOperators (int tempI = 0)
{
i = tempI;
}
binaryOperators operator<< (const binaryOperators &right);
};
binaryOperators operator<< (const binaryOperators &left, const binaryOperators &right)
{
cout << "\nOne";
return left;
}
binaryOperators binaryOperators :: operator<< (const binaryOperators &right)
{
cout << "\nTwo";
return *this;
}
int main ()
{
binaryOperators obj;
// Compiler's behavior: This statement calls the overloaded operator << declared inside the class.
obj << 5 << 3 << 2;
// Compiler's behavior: This statement calls the overloaded operator << declared outside the class.
2 << obj;
return 0;
}
我在 main()
函数中写了注释。
这种编译器行为的原因是什么?
此行为是否依赖于编译器?
Linux 上的 GCC
最佳答案
您看到的行为是由常量正确性引起的。类内部定义的operator<<是非常量的,所以它只能对非常量对象或引用进行操作,比如obj。类外的非成员版本有两个常量操作数。
如果你把成员(member)版写成非成员(member),会是这样的:
binaryOperators operator<< (binaryOperators &left, const binaryOperators &right)
{
cout << "\nTwo";
return left;
}
重载匹配时,编译器会选择最合适的。在第一种情况下,左操作数是非常量,因此它选择成员运算符。在第二种情况下,左操作数是一个右值(临时 binaryOperators),它被引用为 const,因此选择了非成员运算符。
关于c++ - 重载重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8710290/