简体   繁体   English

为什么它是const指针而不是const指针?

[英]Why it is a const pointer rather than pointer to const?

In C++ Primer book, there is an explanation on type aliases as: 在C ++ Primer书中,对类型别名的解释如下:

typedef char *pstring;
const pstring cstr = 0; // cstr is a constant pointer to char

They say that the following is a wrong interpretation: 他们说以下是错误的解释:

const char *cstr = 0;

However it makes sense to me, to replace the typedef alias with its original meaning. 但是,对我而言,将typedef别名替换为其原始含义是有意义的。

In a normal scenario without type aliasing a constant pointer is defined as: 在没有类型别名的正常情况下,常量指针定义为:

char *const cstr = 0;

Why is it constant pointer rather than pointer to const? 为什么它是常量指针而不是const指针?

Can anyone explain in clear terms because the book doesn't seem to clarify it much. 任何人都可以用清晰的术语来解释,因为这本书似乎并没有太多说明。

2 * 3 + 1 is 7. But how come if I do int i = 3 + 1; 2 * 3 + 1是7。但是如果我做int i = 3 + 1;怎么办int i = 3 + 1; and then 2 * i it gives 8? 然后2 * i给8? Shouldn't the variable be replaced with its original meaning? 变量不应该用其原始含义替换吗?

It's because 2 * 3 + 1 is interpreted as (2 * 3) + 1 , while 2 * i is the same as 2 * (3 + 1) . 这是因为2 * 3 + 1被解释为(2 * 3) + 1 ,而2 * i2 * (3 + 1) These mean different things and work out to different numbers. 这些意味着不同的事情,并得出不同的数字。 When you give 3 + 1 a name, when you use the name it doesn't break up the number back into 3 + 1 in order to only multiply the 3. 当您给3 + 1命名时,使用该名称不会将数字分解为3 + 1 ,而只将3乘以3。

The reason that const char * is different from const pstring is very similar. const char *const pstring不同的原因非常相似。 const char * is interpreted as (const char) * ie a pointer to a constant char. const char *被解释为(const char) *即指向常量char的指针。 But const pstring is the same as const (char *) ie a constant pointer to a char. 但是const pstringconst (char *)相同,即指向char的常量指针。 pstring is a whole type by itself, and when you do const pstring it doesn't split up the char * in order to make the char part const. pstring本身是一个整体类型,当您执行const pstring它不会拆分char *以使char部分成为const。

Note: if you did #define pstring char * then const pstring would be the same as const char * , because macros ( #define s) are just treated as text replacements. 注意:如果你做#define pstring char *然后const pstring 一样的const char * ,因为宏( #define S)只是当作文本替换。

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

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