C++学习笔记——友元

友元:访问其他类的私有成员

在被访问的类中使用firend关键字声明;

  • 全局函数作为友元,只需要在声明友元关系之前,该函数已经被声明即可;-
  • 类做友元,只需要在声明友元关系之前,该类已经被声明即可;
  • 成员函数做友元,则需要成员函数所属的类在声明友元关系之前已经完全定义,即使成员函数在类中仅仅只是声明也可。
class Teacher;
class GoodGay
{
public:
	GoodGay();
	void visit();
	void visit2();
	Teacher* teacher;
	int sex;
private:
	int age;
};
class Teacher
{
	//友元:访问其他类的私有属性;关键字friend
	//全局函数做友元:在类中使用firend声明作为友元的函数;friend function declare;
	friend void goodGay(Teacher& t); //friend 函数声明;
	//类做友元:在类中使用friend声明作为友元的类
	friend class GoodGay;
	//成员函数做友元:在类中使用firend声明作为友元的成员函数;
	friend void GoodGay::visit2();
public:
	char name;
private:
	int sex;
};


void goodGay(Teacher& t)
{
	t.sex = 1;
	cout<<t.sex<<endl;
}

GoodGay::GoodGay()
{
	teacher = new Teacher;
}
void GoodGay::visit()
{
	teacher->sex = 1;
	cout<<"goodGay visit: "<<teacher->name<<endl;
	cout<<"goodGay visit: "<<teacher->sex<<endl;
}
void GoodGay::visit2()
{
	cout<<"goodGay visit2: "<<teacher->name<<endl;
	cout<<"goodGay visit2: "<<teacher->sex<<endl;


}
void test01()
{
	GoodGay gg;
	gg.visit();
	gg.visit2();
}

int main()

{

	test01();

	system("pause");
	return 0;
}

posted @ 2024-06-17 20:09  万舜  阅读(12)  评论(0)    收藏  举报