友元

要在类外访问一个类的私有成员,要通过公有成员函数访问,但是频繁访问会增加程序开销,此时可以考虑c++的友元机制:
友元关系有三种:
1.类外定义的普通函数(友元函数)
2.类外定义的成员函数(友元成员)
3.类外定义的一个类(友元类)

1.友元函数

#include <bits/stdc++.h>
#define LL long long
using namespace std;
class Time {
	public :
		Time (int h, int m, int s);
		friend void display (Time t);
	private :
		int hour;
		int minute;
		int second;
};
Time ::Time(int h, int m, int s) {
	hour = h;
	minute = m;
	second = s;
}
void display (Time t) {
	cout << t.hour << ":" << t.minute << ":" << t.second << endl;
}
int main() {
	Time t1 (10, 13, 56);
	display (t1);
	return 0
}


这里的display函数不属于任何类,加上友元声明后可以访问类中的私有成员,但是没有this指针,因此调用私有成员前要加上类名。

二.友元成员
一个类的成员函数是另一个类的友元

#include <bits/stdc++.h>
#define LL long long
using namespace std;
class Student;
class Teacher {
	public :
		void Rework (Student &p, float y);
};
class Student {
	float grade;
	public :
		Student (float x) {grade = x;}
		void print () {
			cout << "grade=" << grade << endl;
		}
		friend void Teacher::Rework(Student &p, float y); 
};
void Teacher::Rework(Student &p, float y) {
	p.grade = y;
}
int main () {
	Student wuming (80.5);
	Teacher gao;
	wuming.print();
	gao.Rework(wuming , 90.0);
	cout << "修改后的成绩:" << endl;
	wuming.print();
	return 0;
}

结果:

grade=80.5
修改后的成绩:
grade=90

三.友元类
一个类声明为另一个类的友元

#include <bits/stdc++.h>
#define LL long long
using namespace std;
class Array {
	int a [10];
	public :
		int Set ();
		friend class Lookup;
};
class Lookup {
	public :
		void Max (Array x);
		void Min (Array x);
};
int Array::Set() {
	int i;
	cout<< "请输入10个数:"  << endl;
	for (i=0 ; i < 10 ; i ++) {
		cin >> a [i];
	}
	return 1;
}
void Lookup::Max(Array x) {
	int max, i;
	max = x.a [0];
	for (i=0 ; i < 10 ; i ++) {
		if (max < x.a [i]) 
			max = x.a [i];
	}
	cout << "最大值为:" << max << endl; 
}
void Lookup::Min(Array x) {
	int min, i;
	min = x.a [0];
	for (i=0 ; i < 10 ; i ++) {
		if (min > x.a [i]) 
			min = x.a [i];
	}
	cout << "最小值为:" << min << endl; 
}
int main () {
	Array p;
	p.Set();
	Lookup f;
	f.Max(p);
	f.Min(p);
	return 0;
}

结果:

请输入10个数:
11 34 67 98 23 45 76 80 20 36
最大值为:98
最小值为:11
posted @ 2022-04-14 16:08  misasteria  阅读(82)  评论(0编辑  收藏  举报