在Visual Studio 2010中访问变量时甚至出现C2326错误

时间:2015-02-07 06:01:20

标签: c++ 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;
}

Microsoft says

  

代码尝试修改成员变量,这是不可能的。

但在这里我只是试图访问变量而不是修改,但我仍然收到错误。

作为给定here的解决方法,我们可以通过引用传递变量或者可以使其变为静态。但我想知道它是否真的是编译器中的错误,如果不是为什么它必须像这样呢?

1 个答案:

答案 0 :(得分:3)

编译器是对的。来自C ++草案标准N3337:

  

9.8本地班级声明

     

1可以在函数定义中声明一个类;这样的类叫做本地类。本地类的名​​称是其封闭范围的本地名称。本地类位于封闭范围的范围内,并且对函数外部的名称具有与封闭函数相同的访问权限。本地类中的声明不得使用(3.2)具有封闭范围的自动存储持续时间的变量。 [例如:

 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
  

- 结束示例]

相关问题