[C++_6]运算符重载

来源:互联网 发布:ubuntu svn库 编辑:程序博客网 时间:2024/05/16 02:54

12 运算符重载

不能重载的操作符: 三目运算符 ? :  . 也不能重载

只能用成员函数来重载 =  ->  []  ()  (类型转换)  

  ()是个函数对象,必须是成员


12.1  运算符重载方法

运算符重载函数分为两种:1成员函数 2友元函数

声明如下:

ostream&  operator<<(ostream out)const;

friend ostream& operator<<(ostream out , class a)

友元函数总比成员函数多一个参数:类的对象。


12.2 自增/自减重载

区别前后的自增(自减)运算符,声明如下:

friend class& operator++(class a, int i=0)

friend class    operator++(class a)

后自增(自减)设置第二个参数int作为哑元,默认值为零。前自增(自减)返回自己现在的值,所以返回引用类型;后自增(自减)返回旧值,即存储过去值的临时对象,所以为类类型。


#include<iostream>#include<string>using namespace std;class fenshu {  int fenzi ;  int fenmu ;public:  fenshu(int fenzi,int fenmu);  friend ostream& operator<<(ostream& out,const fenshu& f);  friend fenshu operator++(fenshu &f,int i);   //后++友元重载,第二个参数int i 作为哑元  fenshu& operator--();                    //后--成员重载  fenshu&  operator++();                         //前++成员重载  int operator[](string n);  fenshu& operator=(fenshu &f);            //重载=运算符 };fenshu::fenshu(int fz,int fm):fenzi(fz),fenmu(fm){}ostream& operator<<(ostream& out,const fenshu &f){  out<<f.fenzi<<"/"<<f.fenmu<<endl;  return out;}fenshu operator++(fenshu &f,int i){  fenshu old(f);  f.fenzi += f.fenmu;  return old;  }fenshu& fenshu::operator--(){  fenzi -= fenmu;  return (*this);}fenshu& fenshu::operator++(){  (*this).fenzi += (*this).fenmu;  return (*this); }int fenshu::operator[](string name){  if(name == "分子") return fenzi;  else if(name == "分母")return fenmu;  else cout << "error!" << endl;}fenshu& fenshu::operator=(fenshu& f){  if(this == &f) return *this;  //防止自己给自己赋值  else  {this->fenzi = f.fenzi;this->fenmu = f.fenmu;return (*this);  }}int main(){  fenshu a(1,2);  fenshu b(3,4);  fenshu c(7,9);  cout << "a:"<< a <<"b:"<< b <<"c:"<< c;  cout << "++a:"<<++a <<"--b:" << --b <<"c++:"<< c++;  a=c;  cout <<"a:"<< a;  cout << "a[分母]:"<< a["分母"]<<endl;    return 0;}
输出结果:



12.3 []/()运算符重载

//重载操作符复数类操作符#include<iostream>using namespace std;class complex{  int shi;  int xu;public:  complex(double s,double x):shi(s),xu(x){};  //重载<</>>操作符,统一格式必须用友元  friend ostream& operator<<(ostream& out,const complex& c)  {out << c.shi << "+" << c.xu << "i" <<endl;return out;  }  friend istream& operator>>(istream& i,complex& c)  {i>>c.shi;i.ignore(200,'+');i>>c.xu;return i;  }    //重载[]/()运算符  int operator[](char ch)  {if(ch == 's') return this->shi;else if(ch == 'x') return this->xu;else return -1;   }    //类型转换操作符没有返回值类型,且必须是类函数   operator double()  {return (float)1.0*shi;  }  };void func(double a);int main(){  complex c(100,2);  cout << "c = "<<c << endl;  cout << "输入一个复数:a+bi" <<endl;  cin >> c;  cout << "c = " << c << endl;  cout << "实部:" << c['s'] << endl << "虚部" << c['x'] << endl;  cout << "(double)c = " << (double)c << endl;  func(c);//此处形参隐式转换  return 0;}void func(double a){  cout << "隐式转换!" << endl;}


12.4 new/delete []  ->运算符

重载同上,不在赘述

0 0
原创粉丝点击