友元函数的使用

一,友元函数的作用

在类外的函数是无法访问类中的 protected 和 private 变量,当在类中将一个函数声明为 friend 函数A时,

A函数就可以访问类中的所有变量。

二,友元函数的使用

1,普通成员作为类的友员函数

class Base
{
public:
	Base()
		
	{}
	friend void Print(Base& b);
	
	 virtual~Base()
	{}
	 static int a;
private:
	int b;
};


int Base::a=1;

void Print(Base& b)
{
	cout << "I am in friend of Base" << endl;
	cout << "Base   int a=" << b.a << endl;
}
int main()
{
	Base b1;
	First f1;
	
	Print(b1);
	
	return 0;
}

 

2,类的成员函数作为其他类的友元函数

class Base;  //因为Base和First都使用了对方,所以都希望对方在自己前面定义,
             //所以在这里进行前向声明
class First  //必须先定义First类,因为Base类中会使用它的成员
{
public:
	void Print(Base& b);
	
};

class Base
{
public:
	Base()
	{	
	}
	friend void First::Print(Base& b);
	
	 virtual~Base()
	{
	}
	 static int a;
private:
	int b;
};

int Base::a=1;
void First::Print(Base& b)  //还必须将函数在类外定义
{
	cout << "I am friend of Base" << endl;
	cout << "Base  int a=" << b.a << endl;
}

int main()
{
	Base b1;
	First f1;
	
	f1.Print(b1);
	
	return 0;
}

 

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值