为什么我们在这里创建朋友函数.C

Why did we create friend function here.C++

本文关键字:函数 朋友 创建 我们 在这里 为什么      更新时间:2023-10-16
class Accumulator
{
private:
int m_value;
public:
Accumulator() { m_value = 0; } 
void add(int value) { m_value += value; }
// Make the reset() function a friend of this class
friend void reset(Accumulator &accumulator);
};
// reset() is now a friend of the Accumulator class
void reset(Accumulator &accumulator)
 {
// And can access the private data of Accumulator objects
accumulator.m_value = 0;
}
int main()
{
Accumulator acc;
acc.add(5); // add 5 to the accumulator
reset(acc); // reset the accumulator to 0
return 0; 
}

我的意思是在这里建立朋友功能有什么用途?我认为重置已经是成员函数,并且可以轻松访问类累加器的私有成员变量。

用于工作的语法reset(acc);需要是一个免费函数,而不是成员函数,而不是一个需要语法acc.reset()进行调用。

免费功能void reset(Accumulator &accumulator)class Accumulator无关,因此它无法访问私有成员m_value。朋友声明更改后者,并给出了与Accumulator的成员功能相同的函数。


请注意,这在超载运算符时特别有用。例如。operator +应始终将其声明为免费功能,通常为朋友。

reset不是成员函数。实际上,此代码说明了成员函数add与非会员函数reset之间的句法差异,并具有friend名称。

尽管这两个函数都可以访问成员变量,但add通过分配m_value直接做到这一点,而reset必须明确指定accumulator

也在呼叫网站上显示构件/非会员差异,因为使用成员语法,即acc.add(5)来调用add,而reset则使用非成员语法来调用CC_19,即reset0。>

它不是成员函数,但是只需使reset成为CC_22 public成员函数。

class Accumulator
{
private:
    int m_value;
public:
    Accumulator() { m_value = 0; } 
    void add(int value) { m_value += value; }
    void reset();
};
// reset() is now a member of the Accumulator class
void Accumulator::reset()
{
    m_value = 0;
}
int main()
{
    Accumulator acc;
    acc.add(5); // add 5 to the accumulator
    acc.reset(); // reset the accumulator to 0
    return 0; 
}