矩形类中运算符重载【C++】
时间: 1ms 内存:128M
描述:
定义一个矩形类,数据成员包括左下角和右上角坐标,定义的成员函数包括必要的构造函数、输入坐标的函数,实现矩形加法,以及计算并输出矩形面积的函数。要求使用提示中给出的测试函数并不得改动。
两个矩形相加的规则是:决定矩形的对应坐标分别相加,如
左下角(1,2),右上角(3,4)的矩形,与
左下角(2,3),右上角(4,5)的矩形相加,得到的矩形是
左下角(3,5),右上角(7,9)的矩形。
这个规则没有几何意义,就这么定义好了。
输出面积的功能通过重载"<<"运算完成。
本题可以在2383的基础上扩展完成。
输入:
测试函数中第一个矩形直接初始化,第二个矩形通过键盘输入。输入四个数,分别表示第二个矩形左下角和右上角顶点的坐标,如输入2.5 1.8 4.3 2.5,代表左下角坐标为(2.5, 1.8),右上角坐标为(4.3, 2.5)。
输出:
输出两点相加后得到的点的面积。运行测试函数时,p1的顶点是1 1 6 3,如果输入的p2是2.5 1.8 4.3 2.5,计算得到的矩形p3的左下角坐标为(3.5, 2.8),右上角坐标为(10.3, 5.5),输出为p3的面积18.36。
示例输入:
2.5 1.8 4.3 2.5
示例输出:
18.36
提示:
参考答案(内存最优[1092]):
#include<stdio.h>
int main()
{
float a1,b1,a2,b2,s;
scanf("%f%f%f%f",&a1,&b1,&a2,&b2);
a1+=1;
b1+=1;
a2+=6;
b2+=3;
s=(b2-b1)*(a2-a1);
printf("%.2f",s);
return 0;
}
参考答案(时间最优[0]):
//设计一个程序,定义一个矩形类,包括数据成员和函数成员。要求有构造函数、析构函数,完成赋值、修改、显示等功能的接口,并编写main 函数测试,要求用一个对象初始化另一对象。提示: 要确定一个矩形(四边都是水平或垂直方向,不能倾斜),只要确定其左上角和右下角的x 和y 坐标即可,因此应包括四个数据成员,left,right,top,bottom,即左右上下四个边界值。
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle();
Rectangle(double a, double b, double c, double d);
Rectangle(Rectangle &p);
void input(); //输入左下角和右上角的坐标,left<right, bottom<top在运行输入时保证,程序中不必判断
Rectangle operator+(Rectangle &p);
friend ostream& operator<<(ostream& output, Rectangle &p);
private:
double left,bottom,right,top; //左下角坐标和右上角坐标
};
Rectangle::Rectangle(double a,double b,double c,double d)
{
left=a;
bottom=b;
right=c;
top=d;
}
Rectangle::Rectangle(){}
Rectangle::Rectangle(Rectangle &p)
{
left=p.left;
bottom=p.bottom;
right=p.right;
top=p.top;
}
void Rectangle::input() //输入
{
cin>>left>>bottom>>right>>top;
}
ostream& operator<<(ostream& output, Rectangle &p)
{
double width, height, area;
width = p.right - p.left;
height = p.top - p.bottom;
area = height * width;
output<<area<<endl;
return output;
}
Rectangle Rectangle::operator+(Rectangle &p)
{
Rectangle tp;
tp.left = this->left + p.left;
tp.bottom = this->bottom + p.bottom;
tp.right = this->right + p.right;
tp.top = this->top + p.top;
return tp;
}
int main()
{
Rectangle p1(1,1,6,3),p2,p3;
p2.input();
p3=p1+p2;
cout<<p3;
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。