#include <iostream>
using namespace std;
class Box
{
double width;
public:
friend void printWidth(Box box);
void setWidth(double wid);
friend class BigBox;
};
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)
{
cout << "width of box:" << box.width << endl;
}
int main()
{
Box box;
BigBox big;
box.setWidth(10.0);
printWidth(box);
big.print(20,box);
return 0;
}
c++——友元函数
最新推荐文章于 2020-08-30 17:03:43 发布