课堂小练习 设计、定义并实现Complex类
定义一个负数类Complex使得下面的代码能够工作。(课本P145)
#include<iostream> #include<cmath> using namespace std; class Complex{ public: Complex(double n_real,double n_imaginary); Complex(Complex &c1); void add(Complex &c2); double mod(); void show(); private: double real,imaginary; }; Complex::Complex(double n_real=0,double n_imaginary=0):real(n_real),imaginary(n_imaginary){ } Complex::Complex(Complex &c1){ real=c1.real; imaginary=c1.imaginary; } void Complex::add(Complex &c2){ real+=c2.real; imaginary+=c2.imaginary; } double Complex::mod(){ return sqrt(real*real+imaginary*imaginary); } void Complex::show(){ if(imaginary>0) cout<<real<<"+"<<imaginary<<"i"<<endl; else cout<<real<<imaginary<<"i"<<endl; } int main(){ Complex c1(3,5); cout<<"c1="; c1.show(); Complex c2(4.5); cout<<"c2="; c2.show(); Complex c3(c1); cout<<"c3="; c3.show(); c1.add(c2); cout<<"c1+c2="; c1.show(); cout<<"|c1|="; cout<<c1.mod()<<endl; return 0; }
运行结果如下