简体   繁体   English

我如何阅读以下声明?

[英]How do I have to read the following statement?

I liked to refresh my C++ skills and tried to programm a little Object, so I came about this expression: 我喜欢刷新我的C ++技能并试图编写一个小对象,所以我想到了这个表达式:

int (*const vectors)[2];

How do I read it? 我该怎么看? I know that it is declaring a constant pointer pointing to a two dimensional int array. 我知道它是声明一个指向二维int数组的常量指针。

Thank you! 谢谢!

You should use the spiral rule to parse int (*const vectors)[2]; 你应该使用螺旋规则来解析int (*const vectors)[2]; :

  • start from the identifier vectors 从标识符vectors开始
  • handle the unary operators on its right, from left to right, there are none before the ')`. 处理右边的一元运算符,从左到右,')之前没有。
  • handle the qualifiers and unary operators on its left, from right to left: 从左到右处理左侧的限定符和一元运算符:
    • const means vectors is constant, you cannot modify its value. const表示vectors是常量,您无法修改其值。
    • * means pointer: vector is a constant pointer *表示指针: vector是一个常量指针
  • skip the parentheses on both sides and start again: 跳过双方的括号,然后重新开始:
    • [2] means array of 2 . [2]表示2的数组 vector is a constant pointer to one or more arrays of 2 vector是一个指向一个或多个2的数组的常量指针
    • finally: int gives the inner element type. finally: int给出内部元素类型。

vector is a constant pointer to one or more arrays of 2 int . vector是一个指向一个或多个2 int数组的常量指针。

Hence vector can be made to point to an array of arrays of 2 int . 因此,可以使vector指向2 int的数组数组。 For example you can use vector to manipulate a 2D matrix this way: 例如,您可以使用vector以这种方式操纵2D矩阵:

// allocate a 2D identity matrix:
int (*const vectors)[2] = malloc(sizeof(int[2][2]);
vectors[0][0] = vectors[1][1] = 1;
vectors[1][0] = vectors[0][1] = 0;

Note however that vectors must be initialized, not assigned because it is defined as const . 但请注意,必须初始化vectors ,而不是分配vectors ,因为它被定义为const If you intend for vectors to point to a 2D matrix that should not be modified, for example as a function argument, the declaration should be: 如果您希望vectors指向不应修改的2D矩阵,例如作为函数参数,则声明应为:

void print_matrix(const int (*vectors)[2]);

Or 要么

void print_matrix(int const (*vectors)[2]);

Finally, there are subtile differences for the meaning of const in C and C++, but the parsing method describe above applies to both languages. 最后,C和C ++中const的含义存在细微差别,但上面描述的解析方法适用于两种语言。

In a declaration, both prefix * and postfix [] are operators that modify an identifier (or declarator). 在声明中,prefix *和postfix []都是修改标识符(或声明符)的运算符。

The thing is that [] has higher precedence than * , so if you left the parens out, you would declare vectors as an array size 2 of int * const . 问题是[]优先级高于* ,所以如果你把parens排除在外,你会将vectors声明为int * const的数组大小2。

The parens are needed to make vectors a const pointer to int [2] . 需要使用parens使vectors成为int [2]的const指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM