C++友元函数,友元类

#include <iostream>

using namespace std;

class Point;
class Cal
{
protected:
private:
public:
	void distance(const Point& p); //一个类的成员函数作为另外一个类的友元函数
};

class Point
{
protected:
private:
	int xp;
	int yp;
public:
	Point() {};
	Point(int x, int y) :xp(x), yp(y)
	{
	}
	~Point() {}
	//将毫不相关的函数声明为友元函数,可以访问类的内部变量
	friend void printPoint(const Point& a);
	//friend void Cal::distance(const Point& p);
	friend Cal;//友元类,类中的很多函数都可以访问
};

void printPoint(const Point& a)
{
	cout << "xp:" << a.xp << ",yp:" << a.yp << endl;
}

void Cal::distance(const Point& p)
{
	cout << "xp:" << p.xp << ",yp:" << p.yp << endl;
}
int main()
{
	Point p(10, 20);
	printPoint(p); //友元函数具备访问权限
	Cal cal;
	cal.distance(p);

	return 0;
}
posted @ 2025-04-02 15:10  微笑的''80  阅读(4)  评论(0)    收藏  举报