假设以下语句
Typedef string *ptr;
Const ptr cstr;
很多人都认为cstr的真实类型是
Const string *cstr,但这是错误的。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string s("hello world");
string s1("you can not point me");
typedef string *ptrsing;
const ptrsing cstr1 = &s;
ptrsing const cstr2 =&s;
string *const cstr3 =&s;
cstr1 = &s1;
cstr2 = &s1;
cstr3 = &s1;
return 0;
}
错误的原因是把typedef当做文本扩展了,声明const ptr时,const修饰的是ptr指针,这是一个指针,因此定义等价于
String * const cstr。