0
点赞
收藏
分享

微信扫一扫

类和对象————友元friend

婉殇成长笔记 2022-02-18 阅读 135
c++

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

.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 条评论