1.【友元类】:首先明确类与其友元类之间如何声明和定义
假设类A,其友元类B,则B中的函数能访问A中的成员。
习惯上先定义B,但首先提前引用声明A,B中的成员函数的参数是A的引用,A中friend B,这就形成了二者之间的依赖关系。
●通俗一点讲:
友元类先定义,友元类里写函数,函数的参数是原类,原类只需friend。
(竟然有点押韵hhhhhhh)
2.【友元函数】:搞清它和友元类的关系
友元包括友元函数和友元类,
而!【友元类其实包括友元函数】。看我的分析↓
●对于友元函数,只是单个的对这个函数friend,如果想引用一个类中的多个函数,就需要对每一个函数都friend。
但是,对于友元类,只需要对这个类friend,就可以实现它里面的全部函数都friend,要注意每个函数的参数都要有对象的引用。
3.一个函数/类可以被多个类声明为友元类。
注意:要把每个类都写在函数的参数列表里。
附代码讲解:
#include<iostream>
using namespace std;
class Date; //提前引用声明
class Value;
class Time{ //下面要把类Time声明为类Date和类Value的友元类,所以先声明Time
public:
Time(int h, int m, int s):hour(h), minute(m), sec(s){}
void set(Date &,Value &); //Time的成员函数参数是Date和Value的引用
void display(Date &, Value &);
private:
int hour;
int minute;
int sec;
};
class Date{
public:
Date(int m, int d, int y):month(m), day(d), year(y){}
friend Time; //把Time声明为Date的友元类
private:
int month;
int day;
int year;
};
class Value{
public:
Value(int i):vi(i){}
friend Time; //把Time声明为Value的友元类
private:
int vi;
};
void Time::set(Date &d, Value &v){
cin>>hour>>minute>>sec;
cin>>d.month>>d.day>>d.year; //友元类去引用别人的数据成员时,需要注明对象名
cin>>v.vi;
}
void Time::display(Date &d, Value &v){
cout << d.month << "/" << d.day << "/" << d.year << endl;
cout << hour << ":" << minute << ":" << sec << endl;
cout << v.vi << endl;
}
int main(){
Time t1(12,0,0);
Date d1(1,1,2000);
Value v1(520);
t1.set(d1,v1);
t1.display(d1,v1);
return 0;
}
运行通过!