void main() { }

Hello ,world !

常用链接

统计

最新评论

谈谈: 常量指针与指针常量(const Type* and Type* const )

  常量指针,“常量的指针”,它(指针)指向常量,而本身(即其地址)非常量。
  指针常量,“指针的常量”,它(指针)本身是常量 ,而指向的东西并非常量。
呼呼 ... 说的还不是很清楚哦 ,是吧。还就来看看代码吧 !

 

#include <iostream>
#include 
<string>

using namespace std;
int main(int argc,char* argv[])
{
//  ---- test const ptr and ptr const 常量指针与指针常量   
    const   char    c = 'a' ;
    cout 
<< "const   char    c = 'a' ,c : " << c << endl ;
    
char    *pchar = const_cast<char*>(&c) ;
    
*pchar = 'A' ;
    
//c = 'A' ;
    cout << "*pchar(c) = 'A' ; ,c : " << c << endl ;
    cout 
<< "*pchar(c) = 'A' ; ,*pchar : " << *pchar  << endl ;
    
const   char*   const_ptr = "const_ptr" ;  //常量指针 -- 指针所指的值不能改变
    char    temp[] = "ptr_const" ;
    
char* const   ptr_const = temp ; // 指针常量 -- 指针的值(即地址)不能改变
    const_ptr = "Const_ptr" ;       // --OK !
//    const_ptr[0] = 'C' ; //but error ,[C++ Error]  E2024 Cannot modify a const object
    ptr_const[0= 'P' ; // --- OK !
//    ptr_const = "Ptr_const" ; //but error ,[C++ Error]  E2024 Cannot modify a const object
    cout << "const_ptr :" << const_ptr <<endl  ;

    cout 
<< "ptr_const :" << ptr_const << endl  ;
    
string  str = "String" ;
    cout 
<< str << endl ;
    const_ptr 
= str.c_str() ;
    
//const_ptr[0] = 's' ;  //error--Cannot modify a const object
    cout << const_ptr << endl ; // --- 
    str[0= 's' ; // change OK --- 
    cout << const_ptr << endl ; // --- 间接更改 ---
/************************************************************/
    cout 
<< "\n\n\n\n       Hello ,World !" <<endl ;
    system(
"pause");
    
return 0;
}


输出结果:
const   char    c = 'a' ,c : a
*pchar(c) = 'A' ; ,c : a
*pchar(c) = 'A' ; ,*pchar : A
const_ptr :Const_ptr
ptr_const :Ptr_const
String
String
string

 


       Hello ,World !
请按任意键继续. . .

还有一点: “常量指针常量” --- const Type* const Ptr ;// Ptr 即以上所述二者之合 。
若是你有过疑惑,那就上机试试揣摩一下,就会搞定的 !
 

 


 

 

 



 

posted on 2009-07-09 22:31 only 阅读(374) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理