【问题标题】:What does the "friend" keyword mean in C++? [duplicate]C++ 中的“friend”关键字是什么意思? [复制]
【发布时间】:2020-10-11 01:01:00
【问题描述】:

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

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

【问题讨论】:

  • 是operator=还是operator==?

标签: c++


【解决方案1】:

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

原则上,你可以在你的班级里做,没有朋友修饰符,所以签名是

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

但请注意,operator= 不能在类外定义: Demo

【讨论】:

    【解决方案2】:

    这些“函数”不会像x.y(z) 这样直接在对象上调用,其中y() 显然是一个函数调用,而是在行使x = z 时间接调用。

    如果该函数需要访问对象的protectedprivate 内部,这是很常见的,它们需要是friend,因为它们被认为是对象的“外部”。

    【讨论】:

      猜你喜欢
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      • 2014-12-19
      • 2011-01-15
      • 2010-10-21
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多