4-20
定义一个负数类Complex,使得下面的代码能够工作。
complex c1(3,5);//用复数3+5i初始化c1
complex c2=4.5;//用实数4.5初始化c2
c1.add (c2) ;//将c1 与c2相加,结果保存在c1中
c1.show ( ) ;//将c1输出(这时的结果应该是7.5+ 5i)
1 #include <iostream> 2 #include <string> 3 #include <stdio.h> 4 using namespace std; 5 6 class Complex{ 7 private: 8 double r; 9 int i; 10 public: 11 Complex(){}; 12 Complex(double r = 0.0, int i = 0):r(r),i(i){} 13 Complex add(Complex& c){ 14 this->r = this->r + c.r; 15 this->i = this->i + c.i; 16 return *this; 17 } 18 void show(){ 19 cout<<this->r; 20 if(this->i){ 21 cout<<"+"<<this->i<<"i"; 22 } 23 } 24 }; 25 26 int main(){ 27 Complex c1(3,5); 28 Complex c2 = 4.5; 29 c1.add(c2); 30 c1.show(); 31 return 0; 32 }

浙公网安备 33010602011771号