天天看點

指向const的指針和const指針

指向常量的指針 和 常量指針

#include <iostream>
#include <string>
using namespace std;
int main()
{
    typedef string *pstring;
    string s("abc"),s2("ABC");
    const pstring cstr = &s;    //相當于聲明string *const cstr; //常量指針
    //cstr=&s2;   //error: assignment of read-only variable 'cstr'|
    cout<<*cstr<<endl;
//--------------------------------------------------
    //常量指針,不能再指向其它變量
    double d=3.14,d2=4.14;
    double * const pd=&d;
    pd=&d2;     //error: assignment of read-only variable 'pd'|
    cout<<*pd<<endl;
//--------------------------------------------------

    //指向const對象的指針 ,不能通過指針修改其所指空間的值
    double d=3.14;
    const double *pd=&d;    //double const *pd=&d;
    *pd=4.14;   //編繹時: error: assignment of read-only location '* pd'|
    cout<<*pd<<endl;
//--------------------------------------------------

    int arr[][1]={ 1,2,3,4,5,6};    //6行1列
    //int **p=(int **)arr;
    int (*w)[3]=(int (*)[3])arr;    //轉化為 2行3列
    cout<<w[1][1]<<endl;

    return 0;
}

      

在下面的聲明中,圓括号是必不可少的:

int *ip[4];     // array of pointers to int

int (*ip)[4];    // pointer to an array of 4ints