即使在 Visual Studio 2010 中访问变量时也会出现 C2326 错误

C2326 error even while accessing variable in Visual Studio 2010

这已在 lambda 函数的情况下进行了讨论 here。 但是,即使是普通的成员函数,我也遇到过这个。

这段简单的代码演示了:

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 ]