c++ - 关于用括号括起来的声明类型是什么的问题

标签 c++ c++17 language-lawyer declaration

dcl.meaning部分中,它表示:

Thus, a declaration of a particular identifier has the form
T D
where T is of the form attribute-specifier-seq opt decl-specifier-seq and D is a declarator. Following is a recursive procedure for determining the type specified for the contained declarator-id by such a declaration.


[bullet 6] In a declaration T D where D has the form
( D1 )
the type of the contained declarator-id is the same as that of the contained declarator-id in the declaration
T D1
Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.


但是,请考虑以下代码
int main(){
  int* (ptr) = nullptr;
}
在我的示例中,(ptr)遵循(D1)的形式,但是它不是声明符,在我的示例中,完整的声明符是*ptr。根据上面提到的项目符号,(D1)表示DD是声明的声明符(注意强调的部分),也就是说,(D1)是声明的声明符。项目符号6所讨论的只是int (*ptr)形式。项目符号6似乎没有涵盖示例int* (ptr)。那么,如何解释这种情况呢?声明符id(int* (ptr))的类型是什么。如果我误解了项目符号6,如何正确理解项目符号6?还是子弹6是措辞上的缺陷而忽视了这种情况?

最佳答案

您必须继续下一节。项目6仅是一种情况,在这里不适用,因为您的声明的格式不是T (D1)。它的形式为T D以及T = intD = *(ptr)D = *D1(此处与D1 = (ptr)匹配)由 [dcl.ptr] 处理:

In a declaration T D where D has the form

*attribute-specifier-seq_opt cv-qualifier-seq_opt D1

and the type of the identifier in the declaration T D1 is "derived-declarator-type-list T", then the type of the identifier of D is "derived-declarator-type-list cv-qualifier-seq pointer to T". The cv-qualifiers apply to the pointer and not to the object pointed to. Similarly, the optional attribute-specifier-seq appertains to the pointer and not to the object pointed to.


因此,为了知道int *(ptr)的含义,我们首先考虑int (ptr)的含义。现在,您在[dcl.meaning]中的引用开始起作用,说这与int ptr相同。因此,int (ptr)会将标识符ptr声明为int类型。然后,按照我引用的规则,int *(ptr)声明ptr作为指向int的指针。

关于c++ - 关于用括号括起来的声明类型是什么的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63579775/

相关文章:

c++ - sizeof(enum) 与 sizeof(std::underlying_type<Enum>::type) 可以不同吗?

c++ - 如何编译来自 MSDN 的动态虚拟 channel C++ 示例

C++:template<class> 是什么意思?

c++ - 如何使用类型特征将函数的通用引用参数限制为右值引用?

c++ - 为什么 C++ 数组索引值是有符号的而不是围绕 size_t 类型构建的(或者我错了)?

c - 一致的数组参数是 VLA 吗?

c++ - 在头文件中初始化常量特征矩阵

c++ - 使用静态库时未定义的函数引用

c++ - std::vector 出现明显的歧义错误,但它仍然可以编译

c++ - 检测 SFINAE 的 POD 类型的第一个成员