class MyClass {
int value;
public:
int getValue() const; // ← 這裡的 const
void setValue(int v); // 非常量成員函數
};
承諾:該函數不會修改對象的任何非靜態成員變量。
| 對象類型 | 可調用 const 函數 | 可調用非 const 函數 |
|---|---|---|
| 常量對象 (`const MyClass obj`) | ✅ 是 | ❌ 否 |
| 常量引用/指針 (`const MyClass&`, `const MyClass*`) | ✅ 是 | ❌ 否 |
| 非常量對象/引用/指針 | ✅ 是 | ✅ 是 |
同名函數可通過 `const` 區分重載,常見於容器類:
class Vector {
int* data;
public:
int& operator[](size_t i) { return data[i]; } // 非 const 版:可修改
int operator[](size_t i) const { return data[i]; } // const 版:只讀
};
C++ 與數據結構可同步學習。數據結構課程中用到的語言特性有限(指針、引用、類、模板、const 正確性),建議: