如题,要求实现:
1、复数类含两个参数的构造函数,一个为实部,一个为虚部。
2、实现加法运算符重载功能,并实现返回值为复数类。
3、Show出结果。
#include<iostream> using namespace std; class Cmycomplex { private: double real,imag; public: Cmycomplex(double r=0,double i=0);//构造函数设默认值,或者重载构造函数 Cmycomplex operator +(Cmycomplex &);//注意,这里只需要传一个参数,运算符+重载功能上类似自定义的.add()函数 void Set(double x,double y); void Show(); }; Cmycomplex::Cmycomplex(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; } void Cmycomplex::Set(double x,double y) { real=x; imag=y; } void Cmycomplex::Show() { cout << "(" << real << "+" << imag << "i" << ")" << endl; }
//StudybarCommentBegin int main() { Cmycomplex z1(2,3),z2,z3(3); z2=z1+z3; z2.Show();
double x,y; cin>>x>>y; z2.Set(x,y); z3=z1+z2; cout<<"\n"; z3.Show(); } //StudybarCommentEnd
-END
标签:real,double,imag,运算符,加法,重载,Cmycomplex,z2 From: https://www.cnblogs.com/peitongshi/p/17340578.html