全局函数作友元
#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;
}