例如此类。非成员函数有可能执行朋友函数的任务吗?

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();
}

09-04 17:06
查看更多