如果想允许显示不属于当前结构的一个成员函数访问当前结构的数据,
该怎么办?
在结构内部声明这个函数为friend()
friend必须在一个结构内声明
编译器必须读取这个结构的声明理解数据类型的大小,行为方面的规则
类控制哪些代码可以访问它的成员。如果不是一个friend的话,程序员
没法从类外破门而入,不能声明一个新类
把全局函数声明为firend,也可以把另外一个结构的成员函数设置整个结构
声明为friend
//: C05:Friend.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Friend allows special access
// Declaration (incomplete type specification):
struct X;
struct Y {
void f(X*);
};
struct X { // Definition
private:
int i;
public:
void initialize();
friend void g(X*, int); // Global friend
friend void Y::f(X*); // Struct member friend
friend struct Z; // Entire struct is a friend
friend void h();
};
void X::initialize() {
i = 0;
}
void g(X* x, int i) {
x->i = i;
}
void Y::f(X* x) {
x->i = 47;
}
struct Z {
private:
int j;
public:
void initialize();
void g(X* x);
};
void Z::initialize() {
j = 99;
}
void Z::g(X* x) {
x->i += j;
}
void h() {
X x;
x.i = 100; // Direct data manipulation
}
int main() {
X x;
Z z;
z.g(&x);
} ///:~
struct X
告诉编译器,有一个X的struct
在X中,声明Y::f(X*)为一个friend函数
其他两个friend函数,第一个声明将一个全局函数g()作为friend
Z把整个结构当做friend
无输出