运算符重载!
1、实验目的 理解运算符重载(非成员形式和成员形式)、学习重载几类运算符(++,=,!=,+,-,==等)。 2、实验内容 应用VC++6.0的构建一个复数类Complex,试对下列几个运算符进行重载:++,=,!=,+,-,==,其中要求要有成员重载形式和友元重载形式,而且,++运算符要求实现先加和后加两种形式。 class complex{ public: double real; double imag; complex(double x,double y) { real=x; imag=y; } friend complex operator -(complex a,complex b); friend int operator==(complex a,complex b); friend int operator!=(complex a,complex b); complex operator++(); complex operator++(int); complex operator=(complex a) { real=a.real; imag=a.imag; return *this; } void show() { cout<<"real :"<<real<<endl; cout<<"imag :"<<imag<<endl; } complex operator+(complex a,complex b) { complex temp(0.0,0.0); temp.real=a.real+b.real; temp.imag=a.imag+b.imag; return temp; } complex operator-(complex a,complex b) { complex temp(0.0,0.0); temp.real=a.real-b.real; temp.imag=a.imag-b.imag; return temp; } int operator==(complex a, complex b) { if(a.real==b.real&&a.imag==b.imag) return 1; return 0; } int operator!=(complex a ,complex b) { if(a.imag!=b.imag||a.real!=b.real) return 1; return 0; } complex complex::operator ++() { real=real+real; imag=imag+imag; return *this; } complex complex::operator ++(int) { ++real; ++imag; return *this; } { complex com1(1.1,2.2),com2(3.3,4.4),total(1.1,2.2),ca(0.0,0.0),fuzhi(0.0,0.0); if(com1==total) cout<<"you yuan xiang deng"<<endl; if(com1!=com2) cout<<"you yuan bu xiang deng "<<endl; total=com1+com2; ca=com2-com1; cout<<"lei wai jia hao : "<<endl; total.show(); cout<<"you yuan jian hao : "<<endl; ca.show(); fuzhi=com1; cout<<"fu zhi real:"<<endl; fuzhi.show(); //调用成员函数 com1++; ++com2; cout<<"qian zhui"<<endl; com1.show(); //调用成员函数 cout<<"hou zhui :"<<endl; com2.show(); return |
运算符重载!
最新推荐文章于 2018-11-04 13:49:42 发布