我之前有一个问答:Point of declaration in C++ . point-of-declaration 规则很好地适用于许多情况。现在,我对结合此规则使用 auto
感到困惑。
考虑这两个代码:
我。自己声明 x
(我们不希望它起作用):
{
auto x = x;
}
二。用外部 x
声明内部 x
(在 gcc 4.8.x 中会出错):
{
int x = 101; // the outer x
{
auto x = x; // the inner x
}
}
根据声明点规则,它应该可以工作,但不能。似乎标准中还有一条我错过了的规则。问题是,使用auto
时的声明点在哪里?
有两种可能:
我。如果声明点在 =
之后,则在语句末尾:
auto object = expression;
^
Is it here? If it is, why gcc complains?
所以第二个声明是有效的并且必须工作,因为没有 x
而是那个外部声明(之前声明过)。因此 auto x=x
是有效的,内部的 x
应该分配给 101
。
二。如果声明点在 =
之前:
auto object = expression;
^
好吧,这没有任何意义,因为 auto
必须等到看到下面的表达式。例如 auto x;
无效。
更新:我需要一个通过规则声明点解释它的答案。
最佳答案
auto x = x; // inner x
格式不正确。
引用 C++11 标准(重点是我的):
7.1.6.4 auto specifier
...
3 Otherwise, the type of the variable is deduced from its initializer. The name of the variable being declared shall not appear in the initializer expression. ...
所以因为 =
之后的 x
解析为 auto x
中的 x
(如问题中所述你链接了),上面的代码格式不正确。
关于c++ - auto 关键字的声明点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19133452/