四川游戏seo整站优化,绿色食品网站模板,网站开发需要的资源,河北网站建设大全友元介绍
类的友元函数是定义在类外部#xff0c;但有权访问类的所有私有#xff08;private#xff09;成员和保护#xff08;protected#xff09;成员。尽管友元函数的原型有在类的定义中出现过#xff0c;但是友元函数并不是成员函数。
友元可以是一个函数#xf…友元介绍
类的友元函数是定义在类外部但有权访问类的所有私有private成员和保护protected成员。尽管友元函数的原型有在类的定义中出现过但是友元函数并不是成员函数。
友元可以是一个函数该函数被称为友元函数友元也可以是一个类该类被称为友元类在这种情况下整个类及其所有成员都是友元。
如果要声明函数为一个类的友元需要在类定义中该函数原型前使用关键字 friend如下所示
class Box
{double width;
public:double length;friend void printWidth( Box box );void setWidth( double wid );
};声明类 ClassTwo 的所有成员函数作为类 ClassOne 的友元需要在类 ClassOne 的定义中放置如下声明
friend class ClassTwo;友元函数应用代码示例
#include iostreamusing namespace std;class Box
{double width;
public:friend void printWidth( Box box );void setWidth( double wid );
};// 成员函数定义
void Box::setWidth( double wid )
{width wid;
}// 请注意printWidth() 不是任何类的成员函数
void printWidth( Box box )
{/* 因为 printWidth() 是 Box 的友元它可以直接访问该类的任何成员 */cout Width of box : box.width endl;
}// 程序的主函数
int main( )
{Box box;// 使用成员函数设置宽度box.setWidth(10.0);// 使用友元函数输出宽度printWidth( box );return 0;
}
编译执行结果
Width of box : 10友元类应用代码示例
#include iostreamusing namespace std;class Box
{double width;
public:friend void printWidth(Box box);friend class BigBox;void setWidth(double wid);
};class BigBox
{
public :void Print(int width, Box box){// BigBox是Box的友元类它可以直接访问Box类的任何成员box.setWidth(width);cout Width of box : box.width endl;}
};// 成员函数定义
void Box::setWidth(double wid)
{width wid;
}// 请注意printWidth() 不是任何类的成员函数
void printWidth(Box box)
{/* 因为 printWidth() 是 Box 的友元它可以直接访问该类的任何成员 */cout Width of box : box.width endl;
}// 程序的主函数
int main()
{Box box;BigBox big;// 使用成员函数设置宽度box.setWidth(10.0);// 使用友元函数输出宽度printWidth(box);// 使用友元类中的方法设置宽度big.Print(20, box);getchar();return 0;
}
编译执行结果