【问题标题】:Access problem in local class本地类中的访问问题
【发布时间】:2010-10-14 05:00:51
【问题描述】:
void foobar(){
    int local;
    static int value;
     class access{
           void foo(){
                local = 5; /* <-- Error here */
                value = 10;
           }
     }bar;    
}   
void main(){
  foobar();
}

为什么不能在foo() 中访问local 编译? OTOH,我可以轻松访问和修改静态变量value

【问题讨论】:

  • main() 的返回类型必须始终为int

标签: c++ scope local-class


【解决方案1】:

在本地类中,您不能使用/访问封闭范围内的自动变量。您只能使用封闭范围内的静态变量、外部变量、类型、枚举和函数。

【讨论】:

    【解决方案2】:

    来自标准文档Sec 9.8.1

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

    标准文档本身的示例,

    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
    };
    // ...
    }
    

    因此无法访问本地类中的自动变量。将您的本地值设为 static 或全局值,以适合您的设计合适

    【讨论】:

      【解决方案3】:

      local设为静态,然后您应该可以访问它

      【讨论】:

        【解决方案4】:

        可能是因为您可以声明超出函数范围的对象。

        foobar() called // local variable created;
        Access* a = new Access(); // save to external variable through interface
        foobar() finished // local variable destroyed
        
        ...
        
        
        savedA->foo(); // what local variable should it modify?
        

        【讨论】:

          猜你喜欢
          • 2015-05-29
          • 2014-06-28
          • 2012-07-20
          • 1970-01-01
          • 1970-01-01
          • 2013-05-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多