1、利用函数重载处理复数运算
#include<iostream> using namespace std; class complex//定义复数类 { public: complex() { real=0;imag=0; } complex(double r,double i):real(r),imag(i){} complex operator+(complex &c2);//声明重载运算符的函数 void display(); private: double real; double imag; }; complex complex::operator+(complex &c2)//定义重载运算符的函数 { complex c; c.real=real+c2.real; c.imag=imag+c2.imag; return c; } inline void complex::display()//inline显示声明的方式,在函数体实现时在函数返回值类型前加上inline { cout<<"("<<real<<","<<imag<<")"<<endl; } int main() { complex c1(3,4),c2(5,-10),c3; c3=c1+c2;//运算符重载用于复数运算 c3.display(); return 0; }
运算符重载的规则:
重载的形式:
返回类型 operator 运算符号(参数说明)
例如:
类A的加法:
class A{}
int operator+(A &,A&);
非成员函数重载:
#include<iostream> using namespace std; class RMB { public: RMB(int d,int c):yuan(d+c/100),jf(c-c/100*100){} friend RMB operator+(RMB&,RMB&); friend RMB& operator++(RMB&); inline void display() { cout<<(yuan+jf/100.0)<<endl; } protected: int yuan,jf;//元,分 }; RMB operator+(RMB &s1,RMB &s2)//非成员函数重载 { return RMB(s1.yuan+s2.yuan,s1.jf+s2.jf); } RMB& operator++(RMB &s) { s.jf++; s.jf-=s.jf/100*100; s.yuan+=s.jf/100; return s; } int main() { RMB d1(1,60),d2(2,50),d3(0,0); d3=d1+d2; ++d3; d3.display(); return 0; }
重载流插入运算符和流提取运算符
#include<iostream> using namespace std; class complex { public: complex(){real=0;imag=0;} complex(double r,double i):real(r),imag(i){} complex operator+(complex&c2); friend istream& operator>>(istream&,complex&); friend ostream& operator<<(ostream&,complex&);//运算符"<<"重载为友元函数 private: double real; double imag; }; complex complex::operator+(complex &c2)//成员函数的重载 { return complex(real+c2.real,imag+c2.imag); } istream& operator>>(istream& in,complex& c) { in>>c.real>>c.imag; } ostream& operator<<(ostream& put,complex& c)//定义运算符<<重载函数,其中put可以任意定义 { put<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl; } int main() { complex c1(2,4),c2(6,10); complex c3,c4; cin>>c4; cout<<c4; c3=c1+c2; cout<<c3; //重载之后能够直接输出c3的值,编译器会解释为operator<<(cout,c3);后调用重载函数 return 0; }
例题1:利用重载输入输出流求解两点间的距离
//做法1:利用class声明的类
#include<iostream> #include<cmath> using namespace std; class point { public: point(){x=0;y=0;} point(int a,int b):x(a),y(b){} double dis(point ,point); friend istream& operator>>(istream&,point&); friend ostream& operator<<(ostream&,point&); private: int x,y; }; istream& operator>>(istream& in,point& a) { in>>a.x>>a.y; return in; } ostream& operator<<(ostream& out,point &a) { out<<a.x<<a.y; return out; } double point::dis(point a,point b) { double A=a.x-b.x,B=a.y-b.y; return sqrt(A*A+B*B); } int main() { point a,b; cin>>a>>b; cout<<a.dis(a,b)<<endl; return 0; }
2、用struct声明类
#include<iostream> #include<cmath> using namespace std; struct point { int x,y; double dis(point a,point b) { double A=a.x-b.x,B=a.y-b.y; return sqrt(A*A+B*B); }; }; istream& operator>>(istream& in,point& a)//不需要做友元函数的说明 { in>>a.x>>a.y; return in; } ostream& operator<<(ostream& out,point &a) { out<<a.x<<a.y; return out; } int main() { point a,b; cin>>a>>b; cout<<a.dis(a,b)<<endl; return 0; }