#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
发布于 2012-01-03 18:00:06
您看到的行为是由常量正确性引起的。类中定义的operator<<是非常数,因此它只能对非常数对象或引用进行操作,如obj。类外部的非成员版本有两个常量操作数。
如果您以非成员的身份编写成员版本,它将如下所示:
binaryOperators operator<< (binaryOperators &left, const binaryOperators &right)
{
cout << "\nTwo";
return left;
}当重载匹配时,编译器选择最佳匹配。在第一种情况下,左操作数是非常数,因此它选择成员运算符。在第二种情况下,左操作数是一个右值(临时binaryOperators),引用为const,因此选择非成员运算符。
发布于 2012-01-03 18:01:20
这种行为完全有意义:
当成员函数存在并且匹配时,最好优先使用它而不是空闲函数,否则类外部的代码可能会无意中破坏类封装(例如,如果另一个成员函数要使用operator<<).
https://stackoverflow.com/questions/8710290
复制相似问题