To my CSDN

类与类之间的友元函数

把一个类中的成员函数作为另一个类的友元函数

class A;//必须申明,因为第8行用到A,但A在其后定义

class B
{
private:
	int date_b;
public:
void print_a(const A p);//打印友元类A的数据成员

};

class A
{
friend void B::print_a(const A p);	//申明友元,print_a可以访问A的数据成员
private:
	int date_a;
public:
	A(int a=10):date_a(a)//缺省构造函数
	{
	}

};


void B::print_a(const A p)//友元的实现,必须在其 友元申明 之后实现
{
	cout << p.date_a <<endl;
}

友元类

class A
{
friend class B;	//申明友元类,B可以访问A的数据成员
private:
	int date_a;
public:
	A(int a=10):date_a(a)//缺省构造函数
	{
	}

};

class B
{
private:
	int date_b;
public:
	void print_a(const A p)//打印友元类A的数据成员
	{
		cout << p.date_a <<endl;
	}

};

以上两种方式都可以达到从一个类中访问另一个类私有数据成员的目的

#include<iostream>
using namespace std;

int main()
{
	A a;
	B b;
	b.print_a(a);

	return 0;
}

输出结果为类A中的data_a的值10

 

posted @ 2019-04-16 00:18  我叫RT  阅读(182)  评论(0编辑  收藏  举报