四.实验
4-11
#include<iostream> using namespace std; class R{ public: R(double a,double b); double area(); private: double l,w; }; R::R(double a,double b){ l=a; w=b; } double R::area(){ return l*w;} int main() { double l,w,s; cout<<"请输入长和宽:"; cin>>l>>w; R c(l,w) ; s=c.area(); cout<<"矩形的面积为:"<<s<<endl; return 0; }
4-20
#include<iostream> using namespace std; class complex{ public: complex(double a,double b); void add(complex c2); void show(); private: double real,imaginary; }; complex::complex(double a,double b){ real=a; imaginary=b; } void complex::add(complex c2){ real+=c2.real; imaginary+=c2.imaginary; } void complex::show(){ cout<<real<<"+"; cout<<imaginary<<"i"<<endl; } int main() { complex c1(3,5); complex c2(4.5,0); c1.add(c2); c1.show(); return 0; }
五.实验结论
通过本次实验,了解了构造函数,复制构造函数,析构函数的用法以及加深了对类和对象的体会,实验中对照课本例题进行理解和修改,感觉掌握的不是很好。4-20例题输入c2=4.5还不能编译不知道是为什么。