原因:有人说是因为
C++规定赋值运算符“=”只能重载为类的非静态成员函数,而不可以重载为类的友元函数。
不能重载为类的静态成员应该比较容易理解,因为静态成员函数是属于整个类的,不是属于某个对象的,它只能去操作类静态数据成员。而赋值运算符“=”是基于对象操作的。
当把赋值运算符重载为类的友员函数,在程序中执行类对象的赋值语句时,程序就会出现两种矛盾的选择。
(1)因为它认为类中并没有重载赋值运算符的成员函数,所以它根据C++的规则,会去调用相应的构造函数。
(2)但是在全局里,我们已经重载了参数类型为此类类型的赋值运算符函数,而这赋值语句刚好和这函数匹配上了,根据C++的规则,也会去调用这函数。
程序是不允许有矛盾不确定选择的,所以当赋值运算符重载为类的友元函数时,编译器就会提示错误。
from: http://www.cnblogs.com/xyl-share-happy/archive/2012/12/06/2804401.html
http://bbs.csdn.net/topics/390439915
2、流运算符为什么不能重载为成员函数,只能用友元函数重载,cout<<obj;
cout << f1 << f2;
//用重载运算符表示,只能通过友员来实现,如果要用成员函数,则会有cout.operator<<(const F& f),所以这是不可能的.因此只能用友员来实现,operator<<(cout,f) 而cout是ostream型的,因此有以下标准格式.注意不能加const,因为cout是要改变的,会改变里的缓冲成员.
friend ostream& operator<<( ostream& cout, constF&) //输出运算符的标准重载格式.
friend istream& operator>>(istream& is, F& f){ } //输入运算符重载标准格式
#include <iostream>
using namespace std;
class F{
int n;
int d;
public :
F(int n=0, int d=1):n(n),d(d){}
friend ostream& operator<<(ostream& os, const F& f){
os << '[' << f.n << '/' << f.d <<']';
return os;
}
F operator*(const F& o) {
return F(n*o.n,d*o.d);
}
friend F operator/(const F& f1,const F& f2){
return F(f1.n/f2.d,f1.d/f2.n);
}
friend istream& operator>>(istream& is, F& f){
char ch;
is >> f.n >> ch >> f.d;
return is;
}
};
int main()
{
F f1(3,5),f2(11,7),f;
cout << f1 << '*' << f2 << '=' << f1*f2 << endl;
cout << f1 << '/' << f2 << '=' << f1/f2 << endl;
cout << "Input 2 fractions :";
cin >> f1 >> f2;
cout <<"f1=" << f1 << endl;
cout << "f2=" << f2 << endl;
}
from: http://www.cnblogs.com/xyl-share-happy/archive/2012/12/06/2804401.html