定义一个矩形的类;矩阵位置由左上角和右下角组成,在矩形类中要使用已定义的点类,矩形类中要具有以下功能:
1.求矩形的面积;
2.求矩形的周长;
在主函数中,输入左上角点和右下角点的坐标,使用输入的点,定义一个矩形类的对象,计算矩形的周长和面积,并输出计算结果;
#include<iostream>
#include<cmath>
using namespace std;
class point; //先声明 以便rectangle使用
class rectangle
{
private:
double x1,y1,x2,y2,s,c;
public:
rectangle(); //构造函数
void point1(point&);//引用
void point2(point&);
void area();
void circumference();
};
class point
{
private:
double x,y;
public:
point(double x_,double y_):x(x_),y(y_){} //构造函数
point()=default; //不符合构造函数 自动生成默认构造函数
friend void rectangle::point1(point&); //友元函数 可访问point对象的私有成员
friend void rectangle::point2(point&); //友元函数 可访问point对象的私有成员
};
rectangle::rectangle()
{
x1=y1=x2=y2=s=c=0;
}
void rectangle::point1(point& p1)
{
this->x1=p1.x;
this->y1=p1.y;
}
void rectangle::point2(point& p2)
{
this->x2=p2.x;
this->y2=p2.y;
}
void rectangle::area()
{
s=fabs(x1-x2)*fabs(y1-y2);
cout<<"矩形的面积是:"<<s<<endl;
}
void rectangle::circumference()
{
c=fabs(x1-x2)*2+fabs(y1-y2)*2;
cout<<"矩形的周长是:"<<c<<endl;
}
int main()
{
double x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;//输入坐标
rectangle re;
point a(x1,y1); //初始化
point b(x2,y2);
re.point1(a);
re.point2(b);
re.area();
re.circumference();
return 0;
}