定义矩形类,矩形类具有私有的数据成员长和宽,公有的成员函数: 2个参数的构造函数、求矩形长的函数、求矩形宽的函数、求矩形面积的函数,输出长、宽和面积的函数。
定义矩形类的1个对象数组r[5](5个元素)初始化赋值,输出矩形的长、宽和面积。
输出矩形长、宽和面积用2种方法实现。
方法1:调用矩形类的输出函数show()实现,
r[i].show();
方法2:调用不是矩形类的普通输出函数disp()实现,
disp(r,5);
#include <iostream>
using namespace std;
class Rectangle
{
private:
double len,wid; //私有数据
public:
Rectangle() //缺省构造函数置len和wid为0
{
len=0;
wid=0;
}
Rectangle(int i,int j)//有参构造函数置len和wid为对应形参的值
{
this->len=i;
this->wid=j;
}
double perimeter()//求矩形周长
{
return (len+wid)*2;
}
double area()//求面积
{
return (len*wid);
}
void readlen()//取矩形长度
{
cout<<"length:"<<len<<endl;
}
void readwid()//取矩形宽度
{
cout<<"width:"<<wid<<endl;
}
void show()
{
readlen();
readwid();
cout<<"aera:"<<area()<<endl;
}
};
void disp(Rectangle Re[],int count)
{
for(int i=0;i<count;i++)
{
cout<<i<<":";
Re[i].show();
cout<<endl;
}
}
int main()
{
Rectangle A[5] = {Rectangle(2,3),Rectangle(2,4),Rectangle(3,5),Rectangle(4,6),Rectangle(20,34)};
cout<<"first"<<endl;
for(int i=0;i<5;i++)
{
cout<<i<<":";
A[i].show();
cout<<endl;
}
cout<<"second"<<endl;
disp(A,5);
return 0;
}