2,友元作用域
注意到上面的示例代码,友元声明和友元定义之间的依赖关系:比如最后一个例子,由于woman类要声明man类中的成员函数disp为友元函数,因此必须将man类的定义放在woman之前。但是man类中又要对woman类中的数据成员进行操作,所以必须将disp函数的定义放在woman的后面。这个关系要搞清楚,否则编译不成功。
3,友元跟重载函数的关系
如果有多个重载函数的版本,那么可以将其中的一个或者几个设为某个类的友元。其他的函数不受此设置的影响,依然不能访问某类的私有数据成员。例如:
#include <iostream>
#include <string>
#include <map>
using namespace std;
class screen;
void show(const screen &s);
void show(int, int, const screen &);
class screen
{
public:
screen():x(0.0), y(0.0){}
friend void show(const screen &s);
friend void show(int a, int b, const screen &s); // 如果将此行删除,将无法调用该版本的show函数
private:
float x;
float y;
};
void show(const screen &s)
{
cout << s.x << ", " << s.y << endl;
}
void show(int a, int b, const screen &s)
{
cout << s.x + a << ", " << s.y + b << endl;
}
int main(void)
{
screen s;
show(s);
show(100, 200, s);
string word;
getline(cin, word);
return 0;
}
4,友元跟权限标识符的关系
实际上,一个类的友元,不管是友元类、友元成员函数还是友元非成员函数,都必须是public访问权限的,否则无法在类外被调用。
