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;
}

猜你喜欢

转载自blog.csdn.net/weixin_37753215/article/details/81634018