C++中的const详解 1. 常量 (const) 基本常量 1 2 3 const int x = 10 ; cout << x << endl;
常量引用 1 2 3 4 5 6 7 int y = 20 ;const int & ref = y; cout << ref << endl; y = 30 ; cout << ref << endl;
2. 指向常量的指针 (pointer to const) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 const int x = 10 ;const int y = 20 ;const int * ptr = &x; cout << *ptr << endl; ptr = &y; cout << *ptr << endl; int z = 40 ;ptr = &z; z = 50 ; cout << *ptr << endl;
3. 常量指针 (const pointer) 1 2 3 4 5 6 7 8 9 10 int x = 10 ;int y = 20 ;int * const ptr = &x; cout << *ptr << endl; *ptr = 30 ; cout << x << endl;
4. 指向常量的常量指针 (const pointer to const) 1 2 3 4 5 6 7 8 const int x = 10 ;const int y = 20 ;const int * const ptr = &x; cout << *ptr << endl;
5. 记忆方法和语法规则 从右往左读法 1 2 3 const int * ptr; int * const ptr; const int * const ptr;
另一种写法(等价) 1 2 3 int const * ptr; int * const ptr; int const * const ptr;
6. 实际应用示例 函数参数中的使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 void printArray (const int * arr, int size) { for (int i = 0 ; i < size; i++) { cout << arr[i] << " " ; } } void processBuffer (int * const buffer, int size) { for (int i = 0 ; i < size; i++) { buffer[i] *= 2 ; } } void readOnlyAccess (const int * const data, int size) { for (int i = 0 ; i < size; i++) { cout << data[i] << " " ; } }
类中的常量成员 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class MyClass {private : const int constantMember; int * const constantPointer; public : MyClass (int value, int * ptr) : constantMember (value), constantPointer (ptr) { } void show () const { cout << constantMember << endl; cout << *constantPointer << endl; } void modify () { *constantPointer = 30 ; } };
7. 常见错误和注意事项 错误示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 const int x = 10 ;int x = 10 ;int * ptr3 = const_cast <int *>(ptr);
最佳实践 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 void processData (const vector<int >& data) { } class Container { vector<int > data; public : const int & at (size_t index) const { return data[index]; } int & at (size_t index) { return data[index]; } }; unique_ptr<const int > ptr1 (new int (10 )) ; const unique_ptr<int > ptr2 (new int (20 )) ; const unique_ptr<const int > ptr3 (new int (30 )) ;
8. 总结表格
声明
指针本身
指向的值
说明
int* ptr
可修改
可修改
普通指针
const int* ptr
可修改
不可修改
指向常量的指针
int* const ptr
不可修改
可修改
常量指针
const int* const ptr
不可修改
不可修改
指向常量的常量指针
理解这些概念对于编写安全、可维护的C++代码非常重要,它们帮助我们在编译时就发现潜在的错误。