昨天在工作中碰到一个问题,对typedef又有了更深的理解。
int g_a = 10;
typedef const int* CPINT;
void foo(CPINT p)
{
p= &g_a;
}
int main()
{
CPINT pint = new int;
foo(pint);
}</span>一直以为typedef 在使用上有点”等量代换“的意思, 由于别的地方还需要引用
typedef int* PINT;所以我打算不定义const, 而是在函数声明中显示加上const, 于是就变成了下面
typedef int* PINT;
void foo(const PINT p)
{
p= &g_a;
}
error C3892: 'p' : you cannot assign to a variable that is const
错误的意思很明显, p是const,
而不是预想的替换那么简单
const PINT p === 把PINT 替换为 int* ===== const int* p
事实上const PINT p 此时等价于
int* const p
总结来说,
在 const PINT p 的声明里: 此时p不是指针,const直接修饰了p, 现在的p是常量,
它的类型是PINT(我们自己定义的类型),相当于const int p, const long p等等,
const都是直接修饰p的,只不过int,long是系统类型,而PINT是我们定义的类型。
出现这种效果了,就是因为typedef,它把int *定义成一个复合的类型,要从整体上来理解语义,而不是字符替换后来理解语义。
知道这个陷阱之后,理解下面这道题目了就很容易了。
typedef char * pStr;
char str[4] = "abc";
const char *p1 = str;
const pStr p2 = str;
p1++;
p2++; //error C3892: 'p2' : you cannot assign to a variable that is const此时p2 是个常量,不能够更改(自增)。
673

被折叠的 条评论
为什么被折叠?



