"friend"关键字在C++中是什么意思?

What does the "friend" keyword mean in C++?

本文关键字:是什么 意思 C++ friend 关键字      更新时间:2023-10-16

为什么在这种情况下我们需要 friend 关键字?

friend bool operator=(const Stack&<E> s, const Stack&<E> q);

这意味着允许访问Stack 对象的私有成员的 operator= 重载。

原则上,您可以在类中执行此操作,而无需使用朋友修饰符,因此签名将是

bool operator=(const Stack&<E> q) const; // The first operand would be this object

但请注意,运算符=不能在类外定义: 演示

这些"函数"不像x.y(z)那样直接在对象上调用,其中y()显然是函数调用,而是在执行x = z时间接调用。

如果该函数需要访问对象的protectedprivate内部(这是很常见的事情(,则需要friend它们,因为它们被视为对象的"外部"。