typedef用法注意事项

本文探讨了C++中const修饰符与指针结合使用时的含义,通过多个实例演示了如何正确理解const myint mintval这样的声明,揭示了mintval实际上是作为指向int的const指针,而非指向const int的指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
  1. #include <iostream.h>
  2.  int main(void)
  3. {
  4.       int i = 20;
  5.       typedef int *myint;
  6.       const myint mintval = &i;
  7.       cout<<*mintval;
  8.       return 0;
  9. }//运行结果显示为 20

如果将typedef看成宏展开,即
        const myint mint ==► const int* mintval 
//mintval是指向const int的指针
那么也就说mintval指向的int对象的值是不能改变的。
修改代码如下验证这种假设:

    1. #include <iostream.h>
    2.  int main(void)
    3. {
    4.       int i = 20;
    5.       typedef int *myint;
    6.       const myint mintval = &i;
    7.       (*mintval)++;
    8.       cout<<*mintval;
    9.       return 0;
    10. }//运行结果显示为 21

这段代码不但编译通过,并且运行的结果也显示mintval所指向的int对象i被修改了。
这也就是说mintval的类型不是指向const int的指针。

实际上关于const myint mintval的含义应该这样看:
const修饰mintval的类型, 而mintval是一个指向int的指针,
所以const myint mintval表示mintval是指向int的const指针。

修改代码如下验证上述结论:

  1. #include <iostream.h>
  2.  int main(void)
  3. {
  4.       int i = 20;
  5.       int i2 = 30;
  6.       typedef int *myint;
  7.       const myint mintval = &i;
  8.       mintval = &i2;   //编译错误:error C2166: l-value specifies const object
  9.       cout<<*mintval;
  10.       return 0;
  11. }//无法运行

上述结果表明mintval是指向int的const指针的结论是正确的

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值