实验3
1.验证性实验部分
类就相当于C里面的结构体,至少有相似的地方,是可以把多种数据类型的数集合起来的。类同时还包含了对数据进行操作和函数。
对象就是C++里面最主要的一个东西,是程序的主体,是抽象的结果。
构造函数函数名与类名相同,没有返回值,而且会被自动调用。
复制构造函数就是把一个已经存在的对象,类似于复制一样,初始化到另外一个没有赋值或者初始化的对象上。
析构函数不接受任何参数,只是在对象消失之前会出来工作,也就是在对象消失之前自动做的一系列事情。
2.编程实验部分
(1)习题4-11
源代码:
#include<iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(int l,int w)
{
length=l;
width=w;
}
float getArea()
{
return length*width;
}
private:
int length;
int width;
};
void main()
{
Rectangle rec(3,4);
cout<<"矩形面积:"<<rec.getArea()<<endl;
}
运行结果:
(2)习题4-20
源代码:
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(float r=0.0,float i=0.0)
{
real=r;
image=i;
}
void add(Complex b)
{
real=real+b.real;
image=image+b.image;
}
void show()
{
cout<<real<<"+"<<image<<"i"<<endl;
}
private:
float real;
float image;
};
void main()
{
Complex c1(3,5);
Complex c2(4.5);
c1.add(c2);
c1.show();
}
运行结果: