error C2628: 'string' followed by 'char' is illegal (did you forget a ';'?)
發生於類別私有成員宣告:
private:
int num;
string char name; // 錯誤:連續兩個型別
char sex;
C++ 不允許連續書寫兩個型別名稱。編譯器將 string 視為第一個型別,接著看到 char 誤以為是第二個宣告的型別,但缺少分號分隔,因此報錯。
#include
private:
int num;
std::string name; // 正確:單一型別
char sex;
private:
int num;
char* name; // 需手動 new/delete 管理記憶體
char sex;
#include
#include
using namespace std;
class student {
public:
student(int n, string nam, char s) {
num = n; name = nam; sex = s;
cout << "construct called" << endl;
}
~student() { cout << "destruct called." << endl; }
void display() {
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl;
}
private:
int num;
string name; // 已修正
char sex;
};
int main() {
student stud1(10010, "wang", 'm');
stud1.display();
student stud2(10011, "zhang", 'f');
stud2.display();
return 0;
}
using namespace std; 時,string 即為 std::string,無需再加型別。followed by 'char' is illegal 直接暗示「連續出現兩個型別關鍵字」。