如题,要求实现:
1、输入一个复数
2、按后缀那样计算
3、Show出结果。
例如输入:
7 8
输出
(14+8i)
(5+4i)
(7+4i)
#include<iostream> using namespace std; class Cmycomplex { private: double real,imag; public: Cmycomplex(double r=0,double i=0);//构造函数设默认值,或者重载构造函数 void Set(double r,double i); Cmycomplex operator +(Cmycomplex &);//注意,这里只需要传一个参数,运算符+重载功能上类似自定义的.add()函数 friend Cmycomplex operator +(double r,Cmycomplex &);//友元这里传两个参数,friend关键字写在最前面 friend Cmycomplex operator +(Cmycomplex &,double r);//友元这里传两个参数,friend关键字写在最前面 void Show(); }; Cmycomplex::Cmycomplex(double r,double i)//类外定义时无需再写默认值 { real=r; imag=i; } void Cmycomplex::Set(double r,double i) { real=r; imag=i; } Cmycomplex Cmycomplex::operator +(Cmycomplex &z) { Cmycomplex tmp; tmp.real=real+z.real; tmp.imag=imag+z.imag; return tmp; } Cmycomplex operator +(double r,Cmycomplex &z)//类外无需写friend关键字,可看作普通函数,不属于该类 { Cmycomplex tmp; tmp.real=r+z.real; tmp.imag=z.imag; return tmp; } Cmycomplex operator +(Cmycomplex &z,double r)//类外无需写friend关键字,可看作普通函数,不属于该类 { Cmycomplex tmp; tmp.real=z.real+r; tmp.imag=z.imag; return tmp; } void Cmycomplex::Show() { cout << "(" << real << "+" << imag << "i" << ")" << endl; }
//StudybarCommentBegin int main() { Cmycomplex z1(3,4),z2(7),z3,z4(z1); double x,y; cin>>x>>y; z3.Set(x,y); cout<<endl; z3=z3+z2; z3.Show(); z4=2+z4; cout<<endl; z4.Show(); z4=z4+2; cout<<endl; z4.Show(); } //StudybarCommentEnd
-END
标签:11,友元,函数,double,imag,operator,real,tmp,Cmycomplex From: https://www.cnblogs.com/peitongshi/p/17342243.html