Access problem in local class

别来无恙 提交于 2019-12-13 13:05:30

问题


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

Why doesn't access to local inside foo() compile? OTOH I can easily access and modify the static variable value.


回答1:


Inside a local class you cannot use/access auto variables from the enclosing scope. You can use only static variables, extern variables, types, enums and functions from the enclosing scope.




回答2:


From standard docs Sec 9.8.1,

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 can use only type names, static variables, extern variables and functions, and enumerators from the enclosing scope.

An example from the standard docs itself,

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

Hence accessing an auto variable inside a local class is not possible. Either make your local value as static or a global one, whichever looks appropriate for your design.




回答3:


Make local static and then you should be able to access it




回答4:


Probably because you can declare object that lives out of scope of the function.

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?


来源:https://stackoverflow.com/questions/3930204/access-problem-in-local-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!