利用友元求坐标俩点之间的距离

本文通过两个示例介绍了C++中如何定义和使用友元函数:一是全局函数作为友元;二是类成员函数作为另一个类的友元。通过计算两点间距离展示了友元函数如何访问类的私有成员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

全局函数作友元

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <math.h>

class Point
{
public:
	Point(float x, float y)
		:_x(x), _y(y){}
	friend float getDistance(Point &one, Point &another);

private:
	float _x;
	float _y;
};


float getDistance(Point &one, Point &another)
{
	float dx = one._x - another._x;
	float dy = one._y - another._y;

	return sqrt(dx*dx + dy*dy);
}


int _tmain(int argc, _TCHAR* argv[])
{
	Point one(10, 20), another(30, 49);

	float dis = getDistance(one, another);

	cout << dis << endl;
}

类成员函数作友元

#include "stdafx.h"
#include <iostream>
using namespace std;


class Point; //前向声明

class PointManagement
{
public:
	double getDistance(Point &a, Point &b);

};

class Point
{
public:
	Point(double xx, double yy)
		:x(xx), y(yy) {}

	void Getxy();

	friend double PointManagement::getDistance(Point &a, Point &b);

private:
	double x, y;
};

double PointManagement::getDistance(Point &a, Point &b)
{
	double dx = a.x - b.x;
	double dy = a.y - b.y;

	return sqrt(dx*dx + dy*dy); //sqrt 为开平方的函数
}


int _tmain(int argc, _TCHAR* argv[])
{
	Point a(1, 2); Point b(3, 4);

	PointManagement pm;
	double dis = pm.getDistance(a, b);
	cout << dis << endl;

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值