类和对象————友元friend

为使程序中某些特殊函数或类可以访问到私有属性,采用友元技术

.1全局函数做友元

将全局函数声明前加friend 放在类内即可

class Person {

	friend void test(Person &p);		//该全局函数可访问私有属性b
public:

private:
	int b;
};

.2 类做友元

class Person {
	//友元声明,fri类可以访问本类的私有属性
	friend class fri;

public:
	Person() {
		name = "zzh";
		nickname = "zc";
	}
public:
	string name;
private:
	string nickname;
};

class fri {
public :
	fri() {
		p = new Person;					//在堆区为Person指针开辟内存空间
	}
	void acknow() {
		cout << "姓名:" << p->name << endl;
		
		cout << "绰号:" << p->nickname << endl;	//调用私有属性 需要friend声明

	}
private:
	Person * p;		//一个指向Person的指针

};


void test( ) {
	fri wang;

	wang.acknow();

}

.3成员函数作友元 + (成员函数类外实现的规范)

只需在函数声明加上作用域即可 类名::

#include <iostream> 
#include <string >
using  namespace std;

class Person;
class fri {
public :
	fri ();
	void acknow1(); 		//允许访问私有属性 
	void acknow2();			//不允许访问私有属性 

private:
	Person * p;
};


class Person {
friend void fri::acknow1(); 
public:
	Person();
	
	string name;
private:
	string nickname;
};

//类外成员函数实现 
fri::fri() {
	p=new Person;
}

Person::Person() {
		name = "zzh";
		nickname = "zc";
}

void fri::acknow1() {
		cout << "姓名:" << p->name << endl;
		
		cout << "绰号:" << p->nickname << endl;	

}

void fri::acknow2(){
		cout << "姓名:" << p->name << endl;
		
		//cout << "绰号:" << p->nickname << endl;	
}

void test( ) {
	fri wang;

	wang.acknow1();
	wang.acknow2();
}

int main() {

	test();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值