今天給大家分享兩個常見的錯誤:
- (定義對象 || 調用函數) 時提示:“表達式必須包含類類型” 的報錯;
- 對象調用函數時提示:“不可訪問” 的報錯。
一、表達式必須包含類類型
這種報錯會出現在兩種情況:
- 類沒有數據成員時,使用類定義對象時帶括號了;
- 定義類時以指針方式定義,對象調用函數時使用“.”。
代碼實例:
情況一
class test {
public:
void print(int i) {
cout << "i = " << i << endl;
}
};
int main(void) {
// 情況一:類沒有數據成員,定義對象時使用括號
test t();
/********************************/
t.print(1); // 這裏會報錯!!!
system("pause");
return 0;
}
解決方法:把括號去掉!!!
情況二
代碼實例:
class test {
public:
void print(int i) {
cout << "i = " << i << endl;
}
};
int main(void) {
// 情況二:指針對象使用“.”去調用函數
test *t = new test;
/********************************/
t.print(1); // 這裏會報錯!!!
system("pause");
return 0;
}
解決方法:使用"->
"
二、不可訪問
我們使用定義好的對象去調用函數時,有可能會出現以下這種情況:
我們來看代碼:
class test {
void print(int i) {
cout << "i = " << i << endl;
}
};
int main(void) {
test t;
/********************************/
t.print(1); // 這裏發生報錯!!!
system("pause");
return 0;
}
也許有些朋友已經看出來了,也許又有些朋友沒有看出來!
“不可訪問”,其實這是訪問權限不夠造成的。
在test類中,定義的函數print沒有使用public進行修飾,所以print函數是私有的,外部不可以訪問。
當我們在print函數前加上public後問題就解決了!
解決方法:在函數前加上“public:
”
已經沒有報錯了!!!
總結:這些都是很低級的錯誤,歸根結底都是我們自己粗心大意造成的!