c++ - 理解令人困惑的 typedef 语法

标签 c++ c typedef language-lawyer

考虑以下代码片段

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/

相关文章:

c++ - Windows Phone 8.0 C++ 成员初始化

c++ - 字符串比较 vector C++

c++ - CMakeLists - 如何包含源文件和头文件的目录?

c++ - 使用基类静态常量变量构造基类,我可以这样做吗?

c - 如何定义一个指针类型的结构体?

c++ - 有没有办法为模板函数参数定义一个类型?

在 OSX 上编译的 ctime 和时间警告

在使用 fscanf 操作之前检查字符串的大小?

c++ - md5 矢量化 sse* && avx

c++ - 为什么typedef相同的标识符