C++中的常量指針和指針常量

1.概述:ios

const Type * pointer;常量指針(const在*以前,與類型的位置無要求),所指向的地址上的數據是常量,而指向的地址能夠變化。spa

Type * const pointer:指針常量(const在*以後),                         指向的地址是常量,              而地址上的數據能夠改變。指針

2.例子:code

#include "iostream"

#define N 8
using namespace std;

void main(){
    int n1=1;
    int n2=2;
    int * const p1=&n1;//指針常量,
    int const * p2=&n1;//常量指針,

    *p1=3;//指針常量能夠改變指向地址的數據,n1也改變了
    //p1=&n2;//指針常量不能改變指向的地址

    //*p2=3;//常量指針不能夠改變指向地址的數據,
    p2=p1;//常量指針能夠改變指向的地址,n2沒有改變
    cout<<"p1:"<<*p1<<"|"<<"n1:"<<n1<<endl;
    cout<<"p2:"<<*p2<<"|"<<"n2:"<<n2<<endl;

    getchar();
}
相關文章
相關標籤/搜索