为什么我们在这里创建朋友函数.C
Why did we create friend function here.C++
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,即reset
0。>
它不是成员函数,但是只需使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;
}
相关文章:
- 一位朋友将模板函数缩写为clang和gcc
- "朋友"成员函数和 GCC 与 Clang
- C++:让函数成为多个类的朋友?
- 在VS 2017中,朋友通过具有私有析构函数的结构的unique_ptr向量进行迭代失败
- 限制多模板参数朋友函数可访问的类实例的范围
- 朋友定义函数的名称空间是什么
- 朋友函数随机行为
- 如何使专用函数模板成为某个类的朋友?
- 优点和缺点 在类内为大型项目定义的内联朋友助手免费函数
- G++ 和 CLang++ 在模板类中定义了朋友模板函数的不同行为
- 使用朋友函数时,会保护变量
- 如何在CPP文件中使用朋友函数
- 成员函数作为朋友:利普曼第五本书错了吗?
- 我们如何将Ostream函数作为类的成员函数实现,而不是作为朋友函数,以便我可以用作虚拟函数
- 在模板类中编写朋友函数声明的正确方法是什么?
- 如何将指针用于朋友函数作为成员函数的参数
- 在没有朋友的情况下向私有构造函数授予访问权限
- 为什么我们在这里创建朋友函数.C
- 正确的朋友模板函数语法
- 运算符[]使用朋友函数超载