C++友元函数简单示例,point点类与矩形类;

定义一个矩形的类;矩阵位置由左上角和右下角组成,在矩形类中要使用已定义的点类,矩形类中要具有以下功能:

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;
}

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值