定义格式
参数个数的限定非成员函数: 单目运算符:参数表中只有一个参数; 双目运算符:参数表中只有两个参数 成员函数: 单目运算符:参数表中没有参数; 双目运算符:参数表中只有一个参数 不能重载的运算符1、不能重载的运算符有: ::, ., .*, ?: 2、必须重载为成员函数的运算符: [], (), –>, = 3、在类成员函数中重载运算符是不允许返回引用的,会出现“返回局部变量的地址”警告 4、cout << f1 << f2; //用重载运算符表示,只能通过友员来实现 //如果要用成员函数,则会有cout.operator<<(const F& f),所以这是不 // 可能的.因此只能用友员来实现,operator<<(cout,f) // 而cout是ostream型的,因此有以下标准格式.注意不能加const,因为 //cout是要改变的,会改变里的缓冲成员. ostream& operator<<( /* 不能加const */ 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; } 单目运算符重载
//单目运算符重载 //把后++,后--当作双目运算符,第二个操作数是整形. #include <iostream> using namespace std; class A{ int data; public : A(int d=0):data(d){} friend ostream& operator<<(ostream& os,const A& a){ os << a.data; return os; } friend istream& operator>>(istream& is,A& a){ is >> a.data; return is; } friend A& operator++(A& a){ a.data += 10; return a; } A& operator--(){ data -= 10; return *this; } friend A/* 不能用引用 */ operator++(A& a,int){ A old(a); a.data += 1; return old; } A /* 不能用引用 */ operator--(int){ A old(*this); data -= 1; return old; } }; int main() { A a1(50),a2(100); cout << "a1=" <<a1 << endl; cout << "a2=" <<a2 << endl; cout << "++a1=" << ++a1 << endl; cout << "--a1=" << --a1 << endl; cout << "a1++=" << a1++ << endl; cout << "a1=" <<a1 << endl; cout << "a2--=" << a2-- << endl; cout << "a2=" <<a2 << endl; } 运算符重载提供了一个自己规定运算符式作方式的方法,至少有一个操作数是自定义类型的.基本类型我们是规定不了的. 强制类型转换:类型(数据) --> (不必写返回类型,因为始终与后面的类型是相同的) operator类型(无形参) 只能写成成员函数,不能是友员.
对自定义类型的对象,使用运算符时,总是调用相应的运算符函数 三目运算符不能重载. 等号是双目运算符也可重载,它也只能是成员. 还有点号('.')不能重载. 双冒号(::)不能重载. sizeof(类型)没法重载. #号不是运算符,无所谓重载. '= () [] -> 类型转换'只能是成员函数来重载,其它的随便,我们建议尽量 使用成员函数来写,有点只能用友元,比如输入输出. ================================================== + 双目运算符重载 友元形式:返 operator符号(形1,形2) 成员形式:返 operator符号(形) + 单目运算符重载 友元: 返 operator符号(形参) 成员: 返 operator符号() + 特例 - 先加加 返回 operator符号() - 后加加 返回 operator符号(形,int) - 先减减 返回 operator符号() - 后减减 返回 operator符号(形,int) |
|