实验3 类和对象
实验结论
4-11 定义并实现一个矩形类,有长,宽两个属性,由成员函数计算矩形的面积。
#include <iostream>
using namespace std;
class rectangle{
public:
rectangle(float length, float wide);
float area();
private:
float l, w;
};
rectangle::rectangle(float length, float wide){
l=length;
w=wide;
}
float rectangle::area(){
return l*w;
}
int main() {
float w,l;
cout << "请输入矩形的长和宽:";
cin >> l >> w;
rectangle rec(l,w);
float area =rec.area();
cout <<"矩形的面积是:"<<area<<endl;
return 0;
}
运行结果:
4-20 定义一个负数类Complex,使得下面的代码能够工作。
Complex c1(3,5);
Complex c2=4.5;
c1.add(c2);
c1.show();
#include <iostream>
using namespace std;
class Complex{
public:
Complex(float r1, float i1){ //构造函数及具体实现
r=r1;
i=i1;
}
Complex(float r1){
r=r1;
i=0;
}
void add(Complex &C){ //复制构造函数及具体实现
r+=C.r;
i+=C.i;
}
void show(){
cout<<r<<(i>0 ? '+':'-')<<i<<'i'<<endl;
}
private:
float r,i;
};
int main(){
Complex c1(3,5);
Complex c2=4.5;
c1.add(c2);
c1.show();
return 0;
}
运行结果:
总结与体会
原本我对函数的构造以及实现;复制函数 理解得比较混乱,通过实例,我理解得更加深入了。
对析构函数的具体作用以及什么时候应用仍然比较模糊。
------------------------------------第二次更新-----------------------------------------------------
改进
浏览并且学习了其他同学的博客后,我对上述代码作出了改进。
// 4-11
#include <iostream>
using namespace std;
class rectangle{
public:
rectangle(float length, float wide); //构造函数
rectangle(rectangle &r); //复制构造函数
~rectangle(){} //析构函数
float area(); //计算矩形面积的函数
private:
float l, w;
};
rectangle::rectangle(float length, float wide){ //构造函数的实现
l=length;
w=wide;
}
rectangle::rectangle(rectangle &r){ //复制构造函数的实现
l = r.l;
w = r.w;
}
float rectangle::area(){ //计算矩形面积函数的实现
return l*w;
}
int main() {
float l,w;
cout << "请输入矩形的长和宽:";
cin >> l >> w;
rectangle Rec(l,w);
rectangle rec(Rec);
cout <<"矩形的面积是:"<<rec.area()<<endl;
return 0;
}
// 4-20
#include <iostream>
using namespace std;
class Complex{
public:
Complex(float r1, float i1); //构造函数1
Complex(float r1); //构造函数2
Complex(Complex &C); //复制构造函数
~Complex(){} //析构函数
void add(Complex c); //实现实部相加的函数
void show(); //结果输出函数
private:
float r,i;
};
Complex::Complex(float r1,float i1){
r=r1;
i=i1;
}
Complex::Complex(float r1){
r=r1;
i=0;
}
Complex::Complex(Complex &C){
r=C.r;
i=C.i;
}
void Complex::add(Complex c){
r+=c.r;
i+=c.i;
}
void Complex::show(){
cout<<r<<(i>0 ? '+':'-')<<i<<'i'<<endl;
}
int main(){
Complex c1(3,5);
Complex c2(4.5);
c1.add(c2);
c1.show();
return 0;
}
疑问
原题要求是Complex c2=4.5
该条件下,上述代码会报错。
可是删除复制函数部分就能够成功编译,不清楚是为什么。
况且貌似主函数部分也并没有用到复制函数。