一,友元函数的作用
在类外的函数是无法访问类中的 protected 和 private 变量,当在类中将一个函数声明为 friend 函数A时,
A函数就可以访问类中的所有变量。
二,友元函数的使用
1,普通成员作为类的友员函数
class Base
{
public:
Base()
{}
friend void Print(Base& b);
virtual~Base()
{}
static int a;
private:
int b;
};
int Base::a=1;
void Print(Base& b)
{
cout << "I am in friend of Base" << endl;
cout << "Base int a=" << b.a << endl;
}
int main()
{
Base b1;
First f1;
Print(b1);
return 0;
}
2,类的成员函数作为其他类的友元函数
class Base; //因为Base和First都使用了对方,所以都希望对方在自己前面定义,
//所以在这里进行前向声明
class First //必须先定义First类,因为Base类中会使用它的成员
{
public:
void Print(Base& b);
};
class Base
{
public:
Base()
{
}
friend void First::Print(Base& b);
virtual~Base()
{
}
static int a;
private:
int b;
};
int Base::a=1;
void First::Print(Base& b) //还必须将函数在类外定义
{
cout << "I am friend of Base" << endl;
cout << "Base int a=" << b.a << endl;
}
int main()
{
Base b1;
First f1;
f1.Print(b1);
return 0;
}