c++ const和指針*

左定值,右定向。

左定值:當const在的左側時,指針所指向的值保持不變(或者說,不能通過指針來修改其所指向的值)。

右定向:當const在的右側時,指針所指的方向保持不鏈。

例子 1-1

#include <iostream>
using namespace std;
int main(){
    const char* str1;
    str1 = "mystr1";
    str1[2] = 'c'; // 不允許:str1所指向的內容爲定值(const),因此不允許通過str1修改
    cout << str1 << endl;
}

例子1-2

#include <iostream>
using namespace std;
int main(){
    int a = 8;
    const int* p = &a;
    *p = 9; // 不允許,p所指向的內容爲定值(const),因此不允許通過p修改該值。
    cout << a << endl;
}

例子1-1,1-2都會報錯,指針所值對象爲定值,不可以通過指針進行修改。

error: read-only variable is not assignable

但是左定值情況下可以通過其他方式修改變量值,如下例子1-2b:

#include <iostream>
using namespace std;
int main(){
    int a = 8;
    const int* p = &a;
    // *p = 9; // 不允許,p所指向的內容爲定值(const),因此不允許通過p修改該值。
    a = 9; // 允許,沒有通過p來修改變量值
    cout << a << endl;
}

例子1-3

#include <iostream>
using namespace std;
int main(){
    const char* str1;
    str1 = "mystr1";
    str1 = "mystr1change"; // 允許:創建了一個新對象“mystr1change"並修改str1的指向。
    cout << str1 << endl;
}

例子1-4

#include <iostream>
using namespace std;

int main(){
    int a = 8;
    const int* p = &a;
    int b = 9;
    p = &b; // 允許,p指向一個新的對象b
    cout << *p << endl;
}

例子1-3,1-4程序正確,其直接修改了指針的指向。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章