2014-09-21 77 views
0

比如这个班。有没有可能让非会员功能执行好友功能的任务?一个非成员函数如何实现一个类的朋友函数呢?

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; 
} 
+5

朋友被定义为非会员... – 2014-09-21 03:25:38

+0

私人的想法是,非会员非朋友无法访问它。 – Dani 2014-09-21 03:33:13

回答

1

非会员非朋友功能无法访问或修改私人数据成员。是否有一个原因,你不想提供一个成员函数的void Reset(){m_nValue = 0;}到类的公共接口?

4

哦,我的,这听起来像是作业:一个人为的问题,回答你必须知道,以提出问题。

首先,请注意,friend函数是非成员函数,因为它不是’不是成员。

反正

void Reset(Accumulator& a) 
{ 
    a = Accumulator(); 
} 
0

如果你的意思是访问类的私有成员,是无法做到的。如果你想有一个非成员非友元函数做同样的事情Reset不会在这种特殊情况下,这应该工作:

void notFriendReset(Accmulator& acc) 
{ 
    acc = Accmulator(); 
} 
相关问题