64,688
社区成员
发帖
与我相关
我的任务
分享
int a=1,b=2;
const int* p1=&a;//限制所指向的值的更改
int* const p2=&b;//限制指向的更改
typedef 取的是意义上的同名, 而不是文本替换.
下面是从C++ Primer 4th上摘录的:
指针和 typedef
The use of pointers in typedefs (Section 2.6, p. 61) often leads to surprising results. Here is a question almost everyone answers incorrectly at least once. Given the following,
在 typedef(第 2.6 节)中使用指针往往会带来意外的结果。下面是一个几乎所有人刚开始时都会答错的问题。假设给出以下语句:
typedef string *pstring;
const pstring cstr;
what is the type of cstr? The simple answer is that it is a pointer to const pstring. The deeper question is: what underlying type does a pointer to const pstring represent? Many think that the actual type is
请问 cstr 变量是什么类型?简单的回答是 const pstring 类型的指针。进一步问:const pstring 指针所表示的真实类型是什么?很多人都认为真正的类型是:
const string *cstr; // wrong interpretation of const pstring cstr
That is, that a const pstring would be a pointer to a constant string. But that is incorrect.
也就是说,const pstring 是一种指针,指向 string 类型的 const 对象,但这是错误的。
The mistake is in thinking of a typedef as a textual expansion. When we declare a const pstring, the const modifies the type of pstring, which is a pointer. Therefore, this definition declares cstr to be a const pointer to string. The definition is equivalent to
错误的原因在于将 typedef 当做文本扩展了。声明 const pstring 时,const 修饰的是 pstring 的类型,这是一个指针。因此,该声明语句应该是把 cstr 定义为指向 string 类型对象的 const 指针,这个定义等价于:
// cstr is a const pointer to string
string *const cstr; // equivalent to const pstring cstr