为什么允许使用类型别名作为变量名? [英] Why type alias is allowed as name of variable?
问题描述
什么规则使以下代码编译没有错误:
using integer = int;
struct Foo
{
int integer;
};
int main() {
Foo f;
int integer;
f.integer;
}
使用
当然不是 #define integer int
的简单替代,但是是什么使该代码在 int int;看来显然格式良好?
会导致格式错误?
using
is of course not a simple replacement for #define integer int
, but what makes this code apparently well-formed while int int;
would make it ill-formed?
推荐答案
虽然可以访问在外部作用域中声明的名称,然后隐藏该名称,这有点令人惊讶,但这只是规则的直接应用范围:
While it's a little surprising that one can access a name declared in an outer scope, and then later hide that name , it's just a straightforward application of the rules for scoping:
在块(9.3)中声明的名称是该块的本地名称;它具有块范围.它的潜在范围始于其声明点(6.3.2),并在其块末尾结束.[basic.scope.block]
A name declared in a block (9.3) is local to that block; it has block scope. Its potential scope begins at its point of declaration (6.3.2) and ends at the end of its block. [basic.scope.block]
反过来,名称声明的重点是:
In turn, the point of a name's declaration is:
紧随其完整的声明者(第11条)之后,初始化程序(如果有的话)... [basic.scope.pdecl]
immediately after its complete declarator (Clause 11) and before its initializer (if any)... [basic.scope.pdecl]
因此,当您执行 integerinteger
时,您尚未声明块作用域名称 integer
,这意味着您仍然可以看到全局的 integer
.这也意味着您不能执行整数integer integer =(integer)0
.
So when you do integer integer
, you haven't yet declared the block-scoped name integer
, which means you can still see the global integer
. This also means you cannot do integer integer = (integer)0
.
更容易解释为什么 int int
无法编译. int
是关键字,因此没有句法规则可以将其声明为名称.它与名称看起来像"的规则不匹配.
It's easier to explain why int int
won't compile. int
is a keyword, so no syntactic rule which could declare it as a name would be able to; it doesn't match the rules for "what a name looks like".
有五种令牌:标识符,关键字,文字,运算符和其他分隔符.[lex.token]
There are five kinds of tokens: identifiers, keywords, literals, operators, and other separators. [lex.token]
因为 int
是关键字,所以不能是标识符,这意味着它不能是名称.
Because int
is a keyword, it cannot be an identifier, which means it cannot be a name.
这篇关于为什么允许使用类型别名作为变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!