熟悉题型——类设计( 矩形类定义【C++】)
时间: 1ms 内存:128M
描述:
定义一个矩形类,数据成员包括左下角和右上角坐标,定义的成员函数包括必要的构造函数、输入坐标的函数,以及计算并输出矩形面积的函数。要求使用提示中给出的测试函数并不得改动。
输入:
四个数,分别表示矩形左下角和右上角顶点的坐标,如输入3.7 0.4 6.5 4.9,代表左下角坐标为(3.7, 0.4),右上角坐标为(6.5, 4.9)。
请根据给出的主函数,完成矩形类设计。
输出:
输出一共有3行(请参考提示(hint)中的main函数):
第一行:由输入的坐标确定的矩形对象p1的面积
第二行:由对象复制得到的矩形对象p2的面积
第三行:直接初始化得到的矩形对象p3的面积
示例输入:
3.7 0.4 6.5 4.9
示例输出:
12.6
12.6
10
提示:
参考答案(内存最优[1268]):
#include<iostream>
using namespace std;
class Rectangle
{
public:
Rectangle()
{}
Rectangle(double q,double w,double e,double r):x1(q),y1(w),x2(e),y2(r)
{}
void input()
{
cin>>x1>>y1>>x2>>y2;
}
void output()
{
cout<<(x2-x1)*(y2-y1)<<endl;
}
private:
double x1,x2,y1,y2;
};
int main()
{
Rectangle p1;
p1.input();
p1.output();
Rectangle p2(p1);
p2.output();
Rectangle p3(1,1,6,3);
p3.output();
return 0;
}
参考答案(时间最优[0]):
#include<iostream>
using namespace std;
class Rectangle
{
private:
double x1,x2,y1,y2;
public:
Rectangle();
Rectangle(double,double,double,double);
void input();
void output();
};
Rectangle::Rectangle()
{
x1=x2=y1=y2=0;
}
Rectangle::Rectangle(double x,double y,double m,double n):x1(x),y1(y),x2(m),y2(n){}
void Rectangle::input()
{
cin>>x1>>y1>>x2>>y2;
}
void Rectangle::output()
{
cout<<(x1-x2)*(y1-y2)<<endl;
}
int main()
{
Rectangle p1;
p1.input();
p1.output();
Rectangle p2(p1);
p2.output();
Rectangle p3(1,1,6,3);
p3.output();
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。
