我在这里,因为我需要帮助类型别名和const。 我是一个真正的c ++初学者,我正在从书中学习#34; c ++ primer"。 我的问题是我不明白为什么:
int ival = 10;
const int *p = &ival; // this is a pointer to const
int rval = 15;
int *const ppi = &rval; // this is a const pointer
typedef int *integer; // if i create an alias for the type int
int num = 50;
const integer pr = # // this is not a pointer to const but a pointer to const
// so my book is telling me that this : const int *pr = # is a wrong interpretation
有人可以解释一下为什么会这样吗?我已经研究了指针(基础知识),我无法理解这个
答案 0 :(得分:3)
你应该将const放在右侧,这样会更容易阅读。你是从右到左做的。
const int *p = &ival;
这相当于
int const *p = &ival.
你读它“指向const int的指针”。指针不是常量,它指向的数据是常量。
int * const ppi = &rval;
这里const已经在右侧,你读到“const指向int的指针”。指针是const,它指向的数据不是const。
typedef int *integer;
int num = 50;
const integer pr = #
在这种情况下你有
integer const pr = #
基本上,如果您将integer
替换为int*
:
int* const pr = #
这就是“const指向int的指针”,就像在第二种情况下一样。