# c++-友元函数和友元类

0
9

## 友元函数

• 友元函数和友元类（破坏类的封装性）
• 面向对象编程思想
``````#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cmath>

using namespace std;

class Point;

class PointManager {
public:
double PointDistance(Point &p1, Point &p2);
};

class Point
{

public:
//声明全局函数 PointDistance 是我类Point类的一个友元函数。
//friend double PointDistance(Point &p1, Point &p2);
friend double PointManager::PointDistance(Point &p1, Point &p2);

Point(int x, int y) {
this->x = x;
this->y = y;
}

int getX()
{
return this->x;
}

int getY()
{
return this->y;
}
private:
int x;
int y;

};

double PointManager::PointDistance(Point &p1, Point &p2)
{
double dis;
int dd_x = p1.x - p2.x;
int dd_y = p1.y - p2.y;

dis = sqrt(dd_x*dd_x + dd_y *dd_y);

return dis;
}

# if 0
double PointDistance(Point &p1, Point &p2)
{
double dis;
int dd_x = p1.x - p2.x;
int dd_y = p1.y - p2.y;

dis = sqrt(dd_x*dd_x + dd_y *dd_y);

return dis;
}
#endif

int main(void)
{

Point p1(1, 2);
Point p2(2, 2);

//cout << PointDistance(p1, p2) << endl;

PointManager pm;
cout << pm.PointDistance(p1, p2) << endl;

return 0;
}
``````

## 友元类

``````#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

using namespace std;

class A
{
public:

A(int a)
{
this->a = a;
}

void printA() {
cout << "a = " << this->a << endl;
// B objB(3000);
// cout << objB.b << endl;
}

//声明一个友元类B
friend class B;
private:
int a;
};

class B
{
public:
B(int b)
{
this->b = b;
}
void printB() {
A objA(100);
cout << objA.a << endl;
cout << "b = " << this->b << endl;
}
friend class A;
private:
int b;
};

int main(void)
{
B bObj(200);

bObj.printB();

return 0;
}
``````

<

0