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

标签 c++ visual-studio-2010

这个已经讨论过了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/

相关文章:

C++ 模板 : How to conditionally compile different code based on data type?

c++ - 更改相邻顶点的值并删除自循环

c++ - 忽略 C++ 中自签名证书的 "Certificate Verification"

c++ - 如何为 COM 接口(interface)中的方法生成弃用警告 (c++)

visual-studio-2010 - Dreamweaver CS5 自动格式化源代码就像在 VS2010 中一样 CTRL+K、CTRL+D?

c++ - SetWindowsHookEx(WH_KEYBOARD) 不使用线程 ID

c++ - C++ 编译器如何处理这个初始化列表?

sql-server - 我们应该使用 Visual Studio 2010 进行所有 SQL Server 数据库开发吗?

c++ - Visual Studio 2012 和 2010 - kernel32.lib, windows.h

visual-studio-2010 - 可执行文件未重建,但目标文件已重新编译