考虑以下代码片段
typedef int type;
int main()
{
type *type; // why is it allowed?
type *k ;// which type?
}
我得到一个错误'k' is not declared in this scope
。编译器将 type *k
解析为 type*
和 k
之间的乘法。这个语法是不是很困惑?
为什么 C++ 标准允许 type *type
?因为语法是这样说的?为什么?
最佳答案
type *type; // why is it allowed?
C++11 3.3.2/1 说:
The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any)
所以变量名type
直到使用类型名type
之后才引入;类型名称是声明符期间 type
唯一可用的含义。
type *k ;// which type?
局部变量名隐藏了全局类型名,所以这里选择了。这在 C++11 3.3.10/1 中有描述:
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class.
完全限定类型名称 ::type
当然仍然可用。
关于c++ - 理解令人困惑的 typedef 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8489215/