课堂小练习: 设计、定义并实现complex类

#include<iostream>
#include<cmath>
using namespace std;
class complex{
    public:
        complex(double real0=0,double imaginary0=0);
        complex(complex &p);
        void add(complex);
        void qiumo();
        void show();
    private:
        double real;
        double imaginary;
};
complex::complex(double real0,double imaginary0):real(real0),imaginary(imaginary0){
    cout<<"calling constructor of complex"<<endl;
}
complex::complex(complex &p):real(p.real),imaginary(p.imaginary){
    cout<<"calling constructor of complex copy"<<endl;
}
void complex::add(complex y){
    cout<<"calling constructor of add"<<endl;
    real=real+y.real;
    imaginary=imaginary+y.imaginary;
}
void complex::qiumo(){
    cout<<"calling constructor of qiumo"<<endl;
    double x;
    x=sqrt(real*real+imaginary*imaginary);
    cout<<"模长"<<x<<endl;
}
void complex::show(){
    cout<<"calling constructor of show"<<endl;
    cout<<real<<"+"<<imaginary<<"i"<<endl;
}

int main(){
    complex c1(3,5);
    complex c2(4.5);
    complex c3(c1);
    c1.add(c2);
    c1.qiumo();
    c1.show();
    
}  

 结论:

这个程序但是是在课堂上并没有实现出来,一个原因是时间太短问题,另一个则是因为自己在课后可以更深入的思考,没什么课堂上的压力,写中间的add c1与c2相加的程序这里并没有考虑到函数声明与其后面程序的函数参数并不一致,导致程序出错,好在向同学请教,解决了这个问题,为了更加清晰地观察到整个程序的运行,我在每个被调用的类成员里都添加了输出这一部分,以此使程序更加的清晰易懂。以及书中有一个地方,是c2=4.5,但是只要我加了复制构造函数那么c2=4.5就无法运行会显示编译错误,如果没加就不会出现这样的情况。

评论:

https://www.cnblogs.com/debuild/p/10640459.html

https://www.cnblogs.com/elise00/p/10637773.html

https://www.cnblogs.com/jyf13/p/10628155.html

 

posted on 2019-03-30 22:33  山海yyqx  阅读(152)  评论(1编辑  收藏  举报