day11pm--运算符函数(1)
http://blog.csdn.net/zuheyawen/article/details/7340717
一、双目运算符
运算符重载就是自己写运算符函数,来规定运算符如何工作,有以下两种方法
友元:1、在类中声明friend 2、定义:返回类型 operator +、-、*(形参1,形参2)
obj1+obj2 => operator+(obj1,obj2) 返回值作为计算结果
成员: 直接在类中定义
operator+(形参)
//友员不是成员,友员的应用,没有this //写运算符函数 ,为了让程序员更方便,重新定义新的+ - * / #include <iostream> using namespace std; class A{ int data; public: A(int d=0):data(d){} void show(){ cout<<"data="<<data<<endl; } // friend class B; A operator-(const A&o){ int dif=data-o.data; return A(dif); } A operator*(const A&o){ int dif=data*o.data; return A(dif); } friend A operator+(const A &a1,const A &a2); ///给A 授权 允许A访问其私有成员 (在起内部声明就可以了) }; ///////////////////运算符函数////////////////////////// A operator+(const A &a1,const A &a2){ /// 函数中传递对象是 几乎都是 用引用&&&&&& int sum=a1.data+a2.data; cout<<"美术等方面上的麻烦"; return A(sum); } //class B{ //public: // void twice(A& a){ // a.data*=2; // } //}; int main(){ /*A oa(50); B ob; ob.twice(oa); oa.show();*/ A obj1(40),obj2(50); A obj3,obj4; obj3=operator+(obj1,obj2); obj3.show(); cout<<"///////////////////////////////"<<endl; obj4=obj1+obj2; ///定义新类型的加++++ 运算符函数,写起式子更像数学的式子 obj4.show(); //友员的operator+ cout<<"///////////////////////////////"<<endl; obj3=obj1-obj2; ///内部 operator - 更加简单 obj3.show(); cout<<"///////////////////////////////"<<endl; obj3=obj1*obj2; // 自己怎么规定,运算符怎么工作 obj3.show(); } /*运算符重载就是自己写运算符函数,来规定运算符如何工作*/
#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; } ////////////输入运算符重载 friend istream& operator>>(istream& is,F&f){ char ch; is>>f.n>>ch>>f.d; return is ; } }; int main(){ F f1,f2; cin>>f1>>f2; cout<<"f1="<<f1<<endl; cout<<"f2="<<f2<<endl; }
二、 单目运算符
友元: 返回类型 operator X(形参)
X obj=>operator X(obj)
成员:返回类型 operator X () 不用形参
X obj=>obj.operator X()
//单目运算符 ++ -- //++和–根据位置的不同有四种情况,都可以重载。 // A& operator ++ ();//前置++ // A operator ++ (int);//后置++ // A& operator --();//前置-- // A operator -- (int);//后置-- //至少有一个操作数是自定义类型的。 #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; } //前置-- friend A& operator--(A& a){ a.data-=10; return a; } //后置++ friend A operator++(A& a,int){ //去掉引用& 引用是保证变量返回之后还在,这个是返回之后不在了 A old(a); a.data+=1; return old; } //后置-- friend A operator--(A& a,int){ A old(a); a.data-=1; return old; } }; int main(){ A a1(100),a2(200); cout<<"a1="<<a1<<endl; cout<<"a2="<<a2<<endl; cout<<"++a1="<<++a1<<endl; cout<<"--a2="<<--a2<<endl; cout<<"a1++="<<a1++<<endl; cout<<"a1="<<a1<<endl; cout<<"a2--="<<a2--<<endl; cout<<"a2="<<a2<<endl; }