C++ const


const在C++中用來修飾內置類型變量, 自定義對象, 成員函數, 返回值, 函數參數.
C++ const 允許指定一個語義結束, 編譯器會強制實施這個約束, 允許程序員告訴編譯器某值是保持不變的.如果在編程中確實有某個值保持不變, 就應該明確使用const, 這樣可以獲得編譯器的幫助.

const 修飾普通類型的變量

Case1

#include <iostream>

int main() {
   const int test = 8;
   test = 9;
}

輸出:

error: assignment of read-only variable ‘test’
test = 9;

解析:
test被聲明爲常量, test不能再次被賦值, 否則編譯器在編譯階段就會報錯.

Case2

 #include <iostream>

int main() {
   const int test = 8;
   int test1 = test;
   std::cout << "test: " << test << std::endl;
   std::cout << "test1: " << test1 << std::endl;
}

輸出:

test: 8
test1: 8

解析:
常量可以賦值給其他變量

Case3

#include <iostream>

int main() {
   const int test = 8;
   int *p = (int*)&test;
   std::cout << "test: " << test << std::endl;
   std::cout << "test: " << *p << std::endl;
   *p = 9;
   std::cout << "test: " << *p << std::endl;
   std::cout << "test: " << test << std::endl;
}

輸出:

test: 8
test: 8
test: 9
test: 8

解析:
第3個test的輸出爲9, 而第四個test的輸出仍然爲8. 對常量使用指針進行賦值是危險行爲,會得到非預期結果

Case 4

#include <iostream>

int main() {
   volatile const int test = 8;
   int *p = (int*)&test;
   std::cout << "test: " << test << std::endl;
   std::cout << "test: " << *p << std::endl;
   *p = 9;
   std::cout << "test: " << *p << std::endl;
   std::cout << "test: " << test << std::endl;
}

輸出:

test: 8
test: 8
test: 9
test: 9

解析:
volatile 關鍵字跟 const 對應相反,是易變的,容易改變的意思.所以不會被編譯器優化,編譯器也就不會改變對 a 變量的操作

const修飾指針變量

const修飾指針變量有三種情況

  • const修飾指針指向的內容,內容爲不可變量
  • const修飾指針,指針爲不可變量
  • const 修飾指針和指針指向的內容,則指針和指針指向的內容都爲不可變量

const修飾指針指向的內容,內容爲不可變量

#include <iostream>

int main() {
   int a = 9;
   const int* p = (int*)&a;
   *p = 10;
}

輸出:

error: assignment of read-only location ‘* p’
    *p = 10;

解析: 指針執行的內容不可改變.簡稱左定值, 因爲const位於*號左邊.

const修飾指針,指針爲不可變量

#include <iostream>

int main() {
   int a = 9;
   int* const p = (int*)&a;
   *p = 10;
   std::cout << "p:" << *p << std::endl;
   int b = 10;
   p = &b;
}

輸出:

error: assignment of read-only variable ‘p’
     p = &b;
       ^

解析: 對於 const 指針 p 其指向的內存地址不能夠被改變,但其內容可以改變.簡稱右定向.因爲 const 位於 * 號的右邊.

const 修飾指針和指針指向的內容,則指針和指針指向的內容都爲不可變量

#include <iostream>

int main() {
    int a = 9;
    const int* const p = (int*)&a;
    *p = 10;
    int b = 10;
    p = &b;
}

輸出:

error: assignment of read-only location ‘*(const int*)p’
     *p = 10;
        ^
error: assignment of read-only variable ‘p’
     p = &b;

解析:
這時,const p 的指向的內容和指向的內存地址都已固定,不可改變

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