typedef 的陷阱

昨天在工作中碰到一个问题,对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 是个常量,不能够更改(自增)。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值