C++基础知识(友元)

友元——普通函数中声明的对象可以调用类中的私有成员函数,通过类的成员函数才可以访问类的私有数据。

关键字:friend

#include<iostream>
using namespace std;
 
class CStu
{
private:
	int age;
	void fun()
	{
		age = 12;
		cout << age << endl;
	}
	//将fun1()声明为类CStu的一个友元函数,使得fun1()函数可以使用类中的私有成员或者受保护成员
    friend void fun1();   
};
 
 
void fun1()
{
	CStu stu;
	stu.fun();
}
 
int main()
{
	fun1();
	system("pause");
	return 0;
}

类内成员对于友元函数相当于public

#include<iostream>
using namespace std;
 
class CStu
{
protected:
	int age;
	void fun()
	{
		age = 12;
		cout << age << endl;
	}
	//将fun1()声明为类CStu的一个友元函数,使得fun1()函数可以使用类中的私有成员
	friend void fun1();
	friend int main();
};
 
 
void fun1()
{
	CStu stu;
	stu.fun();
}
 
int main()
{
	//fun1();
	CStu stu1;    //main函数中可以使用类内的私有成员函数
	stu1.fun();
	system("pause");
	return 0;
}

友元类

#include<iostream>
using namespace std;
 
class CStu
{
protected:
	int age;
	void fun()
	{
		age = 12;
		cout << age << endl;
	}
	//将fun1()声明为类CStu的一个友元函数,使得fun1()函数可以使用类中的私有成员
	friend void fun1();
	friend int main();
	friend class CTeach;
};
 
class CTeach
{
public:
	CStu stu2;
	void fun2()
	{
		stu2.fun();
	}
};
 
void fun1()
{
	CStu stu;
	stu.fun();
}
 
int main()
{
	//fun1();
	//CStu stu1;
	//stu1.fun();
	CTeach teach;
	teach.fun2();
	system("pause");
	return 0;
}

使用protected成员有两种方法:继承和友元

使用private成员:友元

友元的特点:①不受访问修饰符的影响,即友元函数或者友元类的访问修饰符可以是public\protected任意一种;

                     ②可以有多个友元。

           缺点:破坏类的封装性,不是迫不得已不使用。

接口函数

#include<iostream>
using namespace std;
 
class CStu
{
protected:
	int age;
	void fun()
	{
		age = 12;
		cout << age << endl;
	}
	//接口函数
public:
	int Get()
	{
		return age;
	}
	void Set()
	{
		age = 123;
	}
	//将fun1()声明为类CStu的一个友元函数,使得fun1()函数可以使用类中的私有成员
	friend void fun1();
protected:
	friend int main();
public:
	friend class CTeach;
};
 
class CTeach
{
public:
	CStu stu2;
	void fun2()
	{
		stu2.fun();
	}
};
 
void fun1()
{
	CStu stu;
	stu.fun();
}
 
int main()
{
	//fun1();
	//CStu stu1;
	//stu1.fun();
	//CTeach teach;
	//teach.fun2();
	CStu stu1;
	stu1.Set();
	int a = stu1.Get();
	cout << a << endl;
	system("pause");
	return 0;
}

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值