Skip to content

Latest commit

 

History

History
172 lines (112 loc) · 2.21 KB

14_友元.md

File metadata and controls

172 lines (112 loc) · 2.21 KB

概要

  • 友元的目的就是==让一个函数或者类访问另一个类中的私有变量==
  • 友元的关键字为 ==friend==
  • 友元的三种实现
    • 全局函数做友元
    • 类做友元
    • 成员函数做友元
	//全局函数做友元
	friend void getFriendFunc(Student* st);

	//Teacher 类是本类的好朋友,可以访问本类中私有成员
	friend class Teacher;

	//成员函数做友元
	friend void GoodGay::visit();
class Teacher;

class Student {

	//Teacher 类是本类的好朋友,可以访问本类中私有成员
	friend class Teacher;

	//全局函数做友元
	friend void getFriendFunc(Student* st);

private:
	int number;

public:
	string name;

public:
	Student(int num) :number(num) {
		name = "same";
		cout << "Student 初始化" << endl;
	}

	~Student() {
		cout << "Student 析构" << endl;
	}
};


class Teacher {
public:
	Student* student;

	Teacher(Student* st) {
		cout << "Teacher 初始化" << endl;
		student = st;
	}


	~Teacher() {
		cout << "Teacher 析构" << endl;
	}


	void showStudent();
};


void Teacher::showStudent() {
	cout << " showStudent : " << this->student->name << endl;
	cout << " showStudent : " << this->student->number << endl;
};



void func() {

	Student st(10);
	getFriendFunc(&st);


	Teacher t(&st);
	t.showStudent();
}

//全局函数
void getFriendFunc(Student* st) {
	cout << "func getFriendFunc : " << st->name << endl;
	cout << "func getFriendFunc : " << st->number << endl;
}


int main() {

	func();

	system("pause");

	return 0;
}
class Building;

class GoodGay {
public:
	GoodGay();

	void visit();
	void visit2();

	Building* building;  //类成员 对象成员
};

class Building {

	//成员函数做友元
	friend void GoodGay::visit();

public:
	int number;

	Building();
private:
	string name;

};


Building::Building() {
	number = 1;
	name = "xiaoye";
}


GoodGay::GoodGay() {
	building = new Building;
}

void GoodGay::visit() {
	cout << building->number << endl;
	cout << building->name << endl;
}


void GoodGay::visit2() {
	cout << building->number << endl;
	//cout << building->name << endl;
}


void func() {

	GoodGay g;
	g.visit();

	g.visit2();
}



int main() {

	func();

	system("pause");

	return 0;
}