C++——友元

在程序中有时私有属性也想让类外特殊的一些函数或类进行访问,就需要用到友元的技术;
友元的目的就是让一个函数或类访问另一个类中私有成员;
友元关键字:friend
友元实现方法:
全局函数做友元;
类做友元;
成员函数做友元;

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

class person {
	//best函数时类的友元函数可以访问类中的私有成员
	friend void best(person *p);
public:
	string name = "caohai";
	person() {
		age = 10;
		score = 100;
	}
private:
	int age;
	int score;
};

void best(person *p)
{
	cout << "age is " << p->age << endl;
}

int main()
{
	person p1;
	best(&p1);
	system("pause");
	return 0;
}

类做友元:

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


class person {

	friend class fri;   //类做友元fri访问person中的私有属性
public:	
	person();
private:
	int age;
	int score;
};
//person类的构造函数在类外声明
person::person() {
	age = 10;
	score = 100;
}

class fri {
public:
	fri();
	void visit();
	person *p;             //要去访问的person对象
};
//fri类的构造函数在类外声明
fri::fri() {
     p = new person;
}
//fri类的visit函数在类外声明
void fri::visit() {
	cout << "age: " << p->age << endl;
	cout << "sccore: " << p->score << endl;
}

void test()
{
	fri f1;
	f1.visit();
}


int main()
{
	test();
	system("pause");
	return 0;
}

成员函数做友元:

#include <iostream>

using namespace std;

class person;    //因为fri中用到person类所以需要实现声明,编译是自上而下;

class fri {
public:

	fri();
	void visit();
	person *per;
};

class person {
	friend void fri::visit();   //需要对其作用域进行定义因为不定义调用的是全局函数
public:
	person();

private:
	int age;
	int score;
};



fri::fri() {
	per = new person;
}

void fri::visit() {
	cout << "age: " << per->age << endl;
}



person::person() {
	age = 24;
	score = 100;
}



void test()
{
	fri f1;
	f1.visit();
}

int main()
{
	test();
	system("pause");
	return 0;
}

learned from:黑马程序员

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值