CV 限定符(const/volatile)僅允許用於非靜態成員函數。 以下場景均非法:
int test() const { ... } // 錯誤:普通函數不能有 const 限定
class Test {
public:
static int test_fun() const; // 錯誤:static 成員函數不能有 const/volatile
};
原因: 靜態成員函數無 this 指針,const 本質是修飾 this 的類型(const ClassName* this),無 this 則無意義。
class Test {
public:
int getValue() const; // 正確:承諾不修改成員變量
void setValue(int v) volatile; // 合法但罕見:針對 volatile 對象
};
| 函數類型 | 允許 cv 限定? |
|---|---|
| 普通函數 | 否 |
| 靜態成員函數 | 否 |
| 非靜態成員函數 | 是 |
遇到此錯誤,檢查函數是否誤加 const/volatile,移除即可。