用運算子過載設計複數類,實現複數的+、-、*、/
阿新 • • 發佈:2019-02-07
#include <iostream> using namespace std; class plurality { private: double a,b; public: plurality(){} plurality(double x,double y) { a=x; b=y; } ~plurality() { } plurality operator+(plurality A) { return plurality(a+A.a,b+A.b); } plurality operator-(plurality A) { return plurality(a-A.a,b-A.b); } plurality operator*(plurality A) { return plurality(a*A.a-b*A.b,b*A.a+a*A.b); } plurality operator/(plurality A) { return plurality((a*A.a+b*A.b)/(A.a*A.a+A.b*A.b),(b*A.a-a*A.b)/(A.a*A.a+A.b*A.b)); } void show() { if(b<0) { cout<<a<<b<<"i"<<endl; } if(b==0) { cout<<a<<endl; } if(b>0) { cout<<a<<"+"<<b<<"i"<<endl; } } }; int main() { plurality A(2,3); plurality B(-1,3); plurality C; C=A+B; C.show(); C=A-B; C.show(); C=A*B; C.show(); C=A+B; C.show(); }