3-4 计算长方形的周长和面积
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
通过本题的练习可以掌握拷贝构造函数的定义和使用方法;
设计一个长方形类Rect,计算长方形的周长与面积。类中有私有数据成员Length(长)、Width(宽),由具有缺省参数值的构造函数对其初始化,函数原型为:Rect(double Length=0, double Width=0); 再为其定义拷贝构造函数,形参为对象的常引用,函数原型为:Rect(const Rect &); 编写主函数,创建Rect对象r1初始化为长、宽数据,利用r1初始化另一个Rect对象r2,分别输出对象的长和宽、周长和面积。
要求: 创建对象 Rect r1(3.0,2.0),r2(r1);
输入
输入两个实数,中间用一个空格间隔;代表长方形的长和宽
输出
共有6行 ;
分别输出r1的长和宽; r1的周长; r1的面积;r2的长和宽; r2的周长; r2的面积;注意单词与单词之间用一个空格间隔
示例输入
56 32
示例输出
the length and width of r1 is:56,32 the perimeter of r1 is:176 the area of r1 is:1792 the length and width of r2 is:56,32 the perimeter of r2 is:176 the area of r2 is:1792
方法一:
复制函数
#include <iostream>
using namespace std;
class rect
{
private:
double len,wide;
public:
rect(double l=0,double w=0)
{
if(l<=0)
len=0;
else
len=l;
if(w<=0)
wide=0;
else
wide=w;
}
rect(const rect&b)//复制函数
{
len=b.len;
wide=b.wide;
}
void show(string k)
{
cout<<"the length and width of "<<k<<" is:"<<len<<","<<wide<<endl;
cout<<"the perimeter of "<<k<<" is:"<<2*(len+wide)<<endl;
cout<<"the area of "<<k<<" is:"<<len*wide<<endl;
}
};
int main()
{
double a,b;
cin>>a>>b;
class rect r1(a,b);
r1.show("r1");
class rect r2(r1);//调用复制函数
r2.show("r2");
return 0;
}
方法二:
复制语句
#include <iostream>
using namespace std;
class rect
{
private:
double len,wide;
public:
rect(double l=0,double w=0)//带默认参数的构造函数
{
if(l<=0)
len=0;
else
len=l;
if(w<=0)
wide=0;
else
wide=w;
}
void show(string k)
{
cout<<"the length and width of "<<k<<" is:"<<len<<","<<wide<<endl;
cout<<"the perimeter of "<<k<<" is:"<<2*(len+wide)<<endl;
cout<<"the area of "<<k<<" is:"<<len*wide<<endl;
}
};
int main()
{
double a,b;
cin>>a>>b;
class rect r1(a,b);
r1.show("r1");
class rect r2=r1;//复制语句
r2.show("r2");
return 0;
}