C++中的friend函数和friend类是一种特殊的关系,它们允许一个函数或类访问另一个类的私有成员。
使用friend函数修改的private数据:
#include <iostream>
using namespace std;
class Count
{
friend void setX(Count &, int);
public:
Count() : x(0)
{
}
void print() const
{
cout << x << endl;
}
private:
int x;
};
void setX(Count &c, int val)
{
c.x = val;
}
int main()
{
Count counter;
cout << "counter.x after instantiation: ";
counter.print();
setX(counter, 8);
cout << "counter.x after call to setX friend function: ";
counter.print();
}