![](/img/trans.png)
[英]How to make non-member function from one file friend with class in other file?
[英]How can a non-member function achieve what a friend function of a class does?
例如此类。 非成员函数有可能执行朋友函数的任务吗?
class Accumulator
{
private:
int m_nValue;
public:
Accumulator() { m_nValue = 0; }
void Add(int nValue) { m_nValue += nValue; }
// Make the Reset() function a friend of this class
friend void Reset(Accumulator &cAccumulator);
};
// Reset() is now a friend of the Accumulator class
void Reset(Accumulator &cAccumulator)
{
// And can access the private data of Accumulator objects
cAccumulator.m_nValue = 0;
}
哦,天哪,这听起来像是作业:一个人为设计的问题,要回答这个问题,您必须知道该问题。
首先,请注意, friend
功能不是成员,因为它不是成员。
无论如何,
void Reset( Accumulator& a )
{
a = Accumulator();
}
非成员,非朋友功能无法访问或修改私有数据成员。 您是否有理由不希望向类的公共接口提供void Reset(){m_nValue = 0;}的成员函数?
如果您的意思是访问班级的私有成员,则不能这样做。 如果您希望在这种特殊情况下执行与Reset
相同的作用的非成员非朋友功能,则应该可以使用:
void notFriendReset(Accmulator& acc)
{
acc = Accmulator();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.