5
void foobar(){
    int local;
    static int value;
     class access{
           void foo(){
                local = 5; /* <-- Error here */
                value = 10;
           }
     }bar;    
}   
void main(){
  foobar();
}

为什么无法访问local内部foo()编译?OTOH 我可以轻松访问和修改静态变量value

4

4 回答 4

1

从标准文档Sec 9.8.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
};
// ...
}

因此访问本地类中的自动变量是不可能的。将您的本地价值作为或全球价值,以适合您的设计static为准。

于 2010-10-14T05:07:51.890 回答
1

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

于 2010-10-14T05:03:47.500 回答
0

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

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?
于 2010-10-14T05:11:04.887 回答
0

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

于 2010-10-14T05:04:52.413 回答