const與指標¶
const 修飾的是它右邊的東西。
因此可以把它想成:
有兩個東西可以改:
- 改資料:
*ptr = 20 - 改指向:
ptr = &other
#include <iostream>
using namespace std;
int main() {
int first = 10;
int second = 20;
const int* readOnly = &first;
cout << *readOnly << '\n';
readOnly = &second; // 可改指向
int* const fixed = &first;
*fixed = 99; // 可改目標
const int* const fixedReadOnly = &second;
cout << *fixedReadOnly << '\n';
}
記憶技巧:從變數名稱往外讀。