C++之 运算符重载

来源:互联网 发布:mac pro display 编辑:程序博客网 时间:2024/05/21 15:43

主要探索关于在类内部定义运算符重载和定义友元重载

单目运算符重载和双目运算符重载。

在类内定义双目运算符重载和类外双目运算符重载示例:

具体示例:

#include <iostream>#include <string>using namespace std;class complex{private:double _real;double _imag;public:complex():_real(0.0),_imag(0.0){}complex(double r,double i):_real(r),_imag(i){} void display();//重载 +  号   在类内定义双目运算符,只是传递过来一个参数 省略this指针 返回值是一个对象  complex operator+(complex &two){ return complex(_real+two._real,two._imag+_imag);}};void complex::display(){   cout<<_real<<"+"<<_imag<<"i"<<endl;}int main(){  complex one(1,2),two(3,4),thr;  one.display();  two.display();  thr=one+two;  //相当于one.operator(two)  thr.display();  return 0;}

运算结果:


在通过友元进行运算符重载和双目运算符重载示例:

具体示例:

#include <iostream>#include <string>using namespace std;class complex{private:double _real;double _imag;public:complex():_real(0.0),_imag(0.0){}complex(double r,double i):_real(r),_imag(i){} void display();  friend complex operator+(complex &one,complex &two);};//传递参数是两个  最大差别complex operator+(complex &one,complex &two){ return complex(one._real+two._real,two._imag+one._imag);}void complex::display(){   cout<<_real<<"+"<<_imag<<"i"<<endl;}int main(){  complex one(1,2),two(3,4),thr;  one.display();  two.display();  thr=one+two; //相当于one two 参数  thr接收返回值结果  thr.display(); // one.display();  return 0;}

运行结果:


单目运算符:

#include <iostream>#include <string>using namespace std;//定义一个进行加法运算的类class add{private :int _num;public :add():_num(0){}add(int num):_num(num){}void display();   //定义前置自增运算符++    add operator++(){  _num++;return *this;  //返回当前对象}//定义后置自增运算符++add operator++(int){add temp(*this);_num++;return temp;}};void add::display(){ cout<<this->_num<<endl;}int main(){   add old(1),news;   cout<<"old  :";   old.display();   ++old;   cout<<"++old:";   old.display();   news = old++;   cout<<"news :";   news.display();   cout<<"old++:";   old.display();   return 0;}

运算结果:


原创粉丝点击