【问题标题】:Inner Class access内部类访问
【发布时间】:2011-07-14 13:13:15
【问题描述】:

用另一个类(内部类)的方法编写的类可以访问方法变量吗?我的意思是在下面的代码中:

class A
{
  void methodA( int a )
  {
    class B
    {
      void processA()
      {
         a++;
      }
    };
     std::cout<<"Does this program compile?";
     std::cout<<"Does the value of the variable 'a' increments?";
  };

};

这合法吗?'a' 的值会增加吗?请提出建议。

谢谢, 帕万。

【问题讨论】:

  • comeaucomputing.com/tryitout "第 9 行:错误:不允许引用封闭函数的局部变量"
  • 实际上,我在一个远程位置,我在这个 m/c 中没有编译器 :(
  • @user844631 - 查看ideone.com - 以您选择的语言运行小型代码示例的好网站。

标签: c++ nested-class


【解决方案1】:

不,这是不合法的
class BmethodA()本地类

class B 无法访问封闭函数的非静态“自动”局部变量。但它可以从封闭范围访问静态变量。

对于本地类可以访问的内容有几个限制。

这是来自 C++ 标准的参考:

9.8 本地类声明 [class.local]

  1. 可以在函数定义中定义一个类;这样的类称为本地类。本地类的名​​称在其封闭范围内是本地的。本地类在封闭作用域的范围内,并且对函数外部的名称具有与封闭函数相同的访问权限。本地类中的声明只能使用类型名称、静态变量、外部变量和函数以及封闭范围内的枚举数。

[示例:

int x;
void f()
{
   static int s ;
   int x;
   extern int g();

   struct local {
      int g() { return x; } // error: x is auto
      int h() { return s; } // OK
      int k() { return ::x; } // OK
      int l() { return g(); } // OK
   };
// ...
}
local* p = 0; // error: local not in scope

——结束示例]

2.封闭函数对本地类的成员没有特殊的访问权限;它遵守通常的访问规则(第 11 条)。本地类的成员函数应在其类定义中定义(如果已定义)。

3.如果类 X 是本地类,则嵌套类 Y 可以在类 X 中声明,然后在类 X 的定义中定义,或者稍后在与类 X 的定义相同的范围内定义。嵌套在本地类中的类是本地类。

4.本地类不应有静态数据成员。

【讨论】:

    【解决方案2】:

    简短的回答,不。 C++ 中的本地类无法访问它们的封闭函数变量(有一些警告)。您可以阅读更多关于 C++ 本地类 here 的信息,也可以查看此 nice SO answer。强调:

    本地类在函数定义中声明。本地类中的声明只能使用类型名称、枚举、封闭范围内的静态变量以及外部变量和函数。

    int x;                         // global variable
    void f()                       // function definition
    {
          static int y;            // static variable y can be used by
                                   // local class
          int x;                   // auto variable x cannot be used by
                                   // local class
          extern int g();          // extern function g can be used by
                                   // local class
    
          class local              // local class
          {
                int g() { return x; }      // error, local variable x
                                           // cannot be used by g
                int h() { return y; }      // valid,static variable y
                int k() { return ::x; }    // valid, global x
                int l() { return g(); }    // valid, extern function g
          };
    }
    
    int main()
    {
          local* z;                // error: the class local is not visible
    // ...}
    

    【讨论】:

    • 嗯,好的,将编辑我的答案并将嵌套替换为本地。我有一种直觉,虽然它不会改变答案;-)
    猜你喜欢
    • 2016-05-16
    • 2011-02-17
    • 2017-05-31
    • 2014-02-11
    • 2021-04-27
    • 2013-10-25
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    相关资源
    最近更新 更多