c++ - 一个类的方法中的本地类是这个类的 friend 吗?

标签 c++ class friend

我有一个外部类 A。它有一个方法A::fun。在这个方法中,它有一个本地或内部类 B。我的问题是:BA 的 friend 吗?

我认为不是。这样对吗?如果是这样,我认为让 B 类成为 A 的 friend 是非常有益的,因为 B 可以访问 A' s 私有(private)和 protected 成员。而且,由于 B 在方法中是本地的,其他人无法访问它,因此作为 A 的友元是安全的。如何让 B 访问 A 的私有(private)和 protected 成员?

最佳答案

不,他们不是 friend 。

但是局部类对函数外部的名称具有与函数本身相同的访问权限。

标准说:

9.8 Local class declarations [class.local]

A class can be declared within a function definition; such a class is called a local class. The name of a local class is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function. Declarations in a local class shall not odr-use (3.2) a variable with automatic storage duration from an enclosing scope.

要考虑的最大区别是您的本地类只能在函数内部访问。

但在那之后:

  • 类的友元是被授予使用类中私有(private)和 protected 成员名称的权限的函数或类。
  • 局部类在封闭作用域的范围内,并且与封闭函数一样具有对函数外部名称的相同访问权限。也就是说,它可以访问该函数所属类的 protected 成员和私有(private)成员。

关于c++ - 一个类的方法中的本地类是这个类的 friend 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18491341/

相关文章:

c++ - 将指针分配给指针时出现段错误

c++ - 需要一个使用 dht_put_item 和 libtorrent 的例子

c++ - 为什么必须在运行时构造字符串?

C++:为什么它不调用析构函数?

c# to vb.net 如何继承多个类?无法转换它。 SharpDevelop 也失败了

php - 如何将 "add a friend"链接转为按钮?它的功能不同于例如 "send message"链接

c++ - 使用具有相同声明的类方法调用全局函数

class - Salesforce - 构造函数名称无效错误

c++ - 私有(private)析构函数友元函数

c++ - 将嵌套的基模板类实例声明为派生类的 friend