这个已经讨论过了here在 lambda 函数的情况下。 但是,即使是普通的成员函数,我也遇到过这个。
这段简单的代码演示了:
int _tmain(int argc, _TCHAR* argv[])
{
int x = 0;
struct A
{
A()
{
int y=x; // error C2326: 'wmain::A::wmain::A(void)' : function cannot access 'x'
}
};
return 0;
}
微软 says
The code tries to modify a member variable, which is not possible.
但在这里我只是试图访问变量而不是修改,我仍然遇到错误。
作为解决方法 here我们可以通过引用传递变量,也可以将其设为静态。但我想知道它是否真的是编译器中的错误,如果不是,为什么它必须是这样的?
最佳答案
编译器是对的。来自 C++ 草案标准 N3337:
9.8 Local class declarations
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 shall not odr-use (3.2) a variable with automatic storage duration from an enclosing scope. [ Example:
int x;
void f() {
static int s ;
int x;
const int N = 5;
extern int q();
struct local {
int g() { return x; } // error: odr-use of automatic variable x
int h() { return s; } // OK
int k() { return ::x; } // OK
int l() { return q(); } // OK
int m() { return N; } // OK: not an odr-use
int *n() { return &N; } // error: odr-use of automatic variable N
};
}
local* p = 0; // error: local not in scope
— end example ]
关于c++ - 即使在 Visual Studio 2010 中访问变量时也会出现 C2326 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28379149/