他们经常来自忘记包含包含函数声明的头文件,例如,该程序将给出“未声明的标识符”错误:
缺少标题
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
要解决它,我们必须包括标题:
#include
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
如果您写入标题并将其正确包含,则标题可能包含错误的include guard。
拼写错误的变量
当您拼写变量时,会出现初学者错误的另一个常见来源:
int main() {
int aComplicatedName;
AComplicatedName = 1; /* mind the uppercase A */
return 0;
}
范围不正确
例如,这个代码会给出一个错误,因为你需要使用std :: string:
#include
int main() {
std::string s1 = "Hello"; // Correct.
string s2 = "world"; // WRONG - would give error.
}
申报前使用
void f() { g(); }
void g() { }
g在首次使用前尚未声明。要修复它,请在f之前移动g的定义:
void g() { }
void f() { g(); }
或者在f前添加g的声明:
void g(); // declaration
void f() { g(); }
void g() { } // definition
随意编辑这个答案。