1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C++实现的复数运算符重载

C++实现的复数运算符重载

时间:2019-07-07 17:32:39

相关推荐

C++实现的复数运算符重载

//#include<iostream>//using namespace std;#include <iostream.h>class Complex{private:double real;double img;public:Complex(double lp=0.0,double rp=0.0);//构造函数Complex(const Complex &rth);//拷贝构造函数Complex &operator =(const Complex& rh);//赋值运算符void Print(){cout<<real<<"+"<<img<<"i"<<endl;}friend Complex operator+(const Complex& lp,const Complex& rp);friend Complex operator-(const Complex& lp,const Complex& rp);friend Complex operator*(const Complex& lp,const Complex& rp);};Complex ::Complex(double t_real,double t_img){real=t_real;img=t_img;}Complex::Complex(const Complex &rth){*this=rth;}Complex& Complex::operator=(const Complex& rth){if (this==&rth)return *this;else{real=rth.real;img=rth.img;return *this;}}Complex operator+(const Complex& cp1,const Complex& cp2){return Complex(cp1.real+cp2.real,cp1.img+cp2.img);}Complex operator-(const Complex& cp1,const Complex& cp2){return Complex(cp1.real-cp2.real,cp1.img-cp2.img);}Complex operator*(const Complex&cp1,const Complex&cp2){return Complex (cp1.real*cp2.real-cp1.img*cp2.img,cp1.real*cp2.img+cp2.real*cp1.img); }int main (){Complex lp(2,3);Complex rp(1,1);Complex res;Complex cb(lp);res=lp+rp;cout<<"The + result: ";res.Print();res=lp-rp;cout<<"The - result: ";res.Print();res=lp*rp;cout<<"The * result: ";res.Print();res=cb;cout<<"The = result: ";res.Print();return 0;}

最近写的关于C++ 复数运算符重载的,特分享一下

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。