C++ Date Structure 3

来源:互联网 发布:宁波院士之乡 知乎 编辑:程序博客网 时间:2024/06/05 19:28

1.运算符重载 头文件

/*  运算符重载 */#ifndef __complex_H__#define __complex_H__class Complex{ private:  double dRealPart;  double dImagePart; public:  Complex(double rp=0,double ip=0);  virtual~Complex(){};    void show(void);  friend Complex operator + (const Complex &a,const Complex &b);  Complex operator -(const Complex &a);    };#endif
2.运算符重写方法实现

/*  运算符重载 */#ifdef _MSC_VER#if _MSC_EVR==1200#include<iostream.h>#else#include <iostream>using namespace std;#endif#else#include<iostream>using namespace std;#endif // judge the type of compiler and chose include files#include "complex.h"Complex::Complex(double rp,double ip){  //操作结果为复数,构造复数  dRealPart=rp;  dImagePart=ip;  } void Complex::show(void){  // 操作结果显示复数  cout<<dRealPart;  if(dImagePart<0 && dImagePart!=-1)    {      cout<<dImagePart<<"i"<<endl;    }  else if(dImagePart==-1)    {      cout<<"-i"<<endl;    }  else if(dImagePart>0 &&dImagePart!=1)    {      cout<<"+"<<dImagePart<<"i"<<endl;    }  else if(dImagePart==1)    {      cout<<"+i"<<endl;    }}Complex operator + (const Complex &a,const Complex &b){  Complex c;  c.dRealPart=a.dRealPart+b.dRealPart;  c.dImagePart=a.dImagePart+b.dImagePart;  return c;}Complex Complex::operator - (const Complex &a){  Complex c;  c.dRealPart=dRealPart-a.dRealPart;  c.dImagePart=dImagePart-a.dImagePart;  return c;}
3.主函数调用

/*  运算符重载 */#ifdef _MSC_VER#if _MSC_EVR==1200#include<iostream.h>#else#include <iostream>using namespace std;#endif#else#include<iostream>using namespace std;#endif // judge the type of compiler and chose include files#include "complex.h"int main(){  Complex z1(6,8);  z1.show();  Complex z2(8,9);  z2.show();  Complex z3;  z3=z1+z2;  z3.show();  Complex z4;  z4=z2-z1;  z4.show();}