const 指针 和 typedef 混合测试

先给出结论:

	typedef int* PINT;           // PINT   <---> int*

	typedef PINT const CPINT1;   // CPINT1 <---> int* const
	typedef const PINT CPINT2;   // CPINT2 <---> int* const

	typedef const int* CPINT3;  // CPINT3 <---> const int*
	typedef int* const CPINT4;	 // CPINT4 <---> int* const 

为搞清楚 const 指针, 特地做了以下的测试:

        // 变量准备
	int nNum1 = 111;    
	int nNum2 = 222;    
	int* pNum1 = &nNum1;
	int* pNum2 = &nNum2;


    // effective c++中这么说:    
    // *号在const左边为const data; (只读指针)  
    // *号在const右边为const pointer;    
    // 之所以要这么记是因为 const int* p等同于int const *p    
    // 我的记法是 const 和变量名在一起的则是 const 指针,反之则是const data.    
        

    // 测试1
    const int* ptr1 ( pNum1); // 初始化    
    //*ptr1 = nNum2;  // error 只读指针。  
    ptr1 = pNum2;     //ok    

    // 测试2    
    int* const ptr2 ( pNum1); // 初始化   
    *ptr2 = nNum2;   // ok    
    //ptr2 = pNum2;  // error, const指针 


这个时候 做了次typedef, 出现了神奇的事情

    typedef int* PINT;
    // 测试3
    const PINT ptr3 ( pNum1); // 初始化    
    *ptr3 = nNum2;     //ok  
    //ptr3 = pNum2;    // error,const指针     
    
    // 测试4
    PINT const ptr4 ( &nNum1); // 初始化   
    *ptr4 = nNum2;    // ok    
    //ptr4 = pNum2;   // error,const指针


非常不解,  继续 typedef 加上const

    typedef PINT const CPINT1;
    typedef const PINT CPINT2;
 
    // 测试5
    CPINT2 ptr5 ( pNum1); // 初始化    
    *ptr5 = nNum2;		//ok  
    //ptr5 = pNum2;    // error,const指针     

    // 测试6    
    CPINT1 ptr6 ( pNum1); // 初始化   
    *ptr6 = nNum2; // ok    
    //ptr6 = pNum2; // error,const指针  

还是一样, 最后 再试。

    typedef const int* CPINT3;
    typedef int* const CPINT4;
    // 测试7
    CPINT3 ptr7 ( pNum1); // 初始化   
    //*ptr7 = nNum2; // error    
    ptr7 = pNum2; // OK 

    // 测试8 : 
    CPINT4 ptr8 ( pNum1); // 初始化   
    *ptr8 = nNum2; // ok    
    //ptr8 = pNum2; // error,const指针
这次觉得结果就跟测试1, 测试2 一样了。 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值