问题
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