什么是未声明的标识符错误?什么是常见原因,我该如何解决?
错误文本示例:
error C2065: 'cout' : undeclared identifier
'cout' 未声明(首次在此函数中使用)
最常见的原因是忘记包含包含函数声明的头文件,例如,这个程序会给出'undeclared identifier'错误:
>
int main() {std::cout <<你好世界!"<<std::endl;返回0;}
要修复它,我们必须包含标题:
#include int main() {std::cout <<你好世界!"<<std::endl;返回0;}
如果您编写了标题并正确包含了它,则标题可能包含错误的include guard.
要了解更多信息,请参阅 http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.
初学者错误的另一个常见原因是变量拼写错误:
int main() {int aComplicatedName;AComplicatedName = 1;/* 注意大写 A */返回0;}
比如这段代码会报错,因为你需要使用std::string
:
#include int main() {std::string s1 = "你好";//正确的.字符串 s2 = "世界";//错误 - 会出错.}
void f() { g();}无效 g() { }
g
在第一次使用之前没有被声明.要修复它,请在 f
之前移动 g
的定义:
void g() { }无效 f() { g();}
或者在f
之前添加一个g
的声明:
void g();//宣言无效 f() { g();}void g() { }//定义
这是特定于 Visual Studio 的.在VS中,您需要在任何代码之前添加#include "stdafx.h"
.编译器忽略之前的代码,所以如果你有这个:
#include #include "stdafx.h"
#include
将被忽略.你需要把它移到下面:
#include "stdafx.h"#include
随意编辑这个答案.
What are undeclared identifier errors? What are common causes and how do I fix them?
Example error texts:
error C2065: 'cout' : undeclared identifier
'cout' undeclared (first use in this function)
They most often come from forgetting to include the header file that contains the function declaration, for example, this program will give an 'undeclared identifier' error:
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
To fix it, we must include the header:
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
If you wrote the header and included it correctly, the header may contain the wrong include guard.
To read more, see http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.
Another common source of beginner's error occur when you misspelled a variable:
int main() {
int aComplicatedName;
AComplicatedName = 1; /* mind the uppercase A */
return 0;
}
For example, this code would give an error, because you need to use std::string
:
#include <string>
int main() {
std::string s1 = "Hello"; // Correct.
string s2 = "world"; // WRONG - would give error.
}
void f() { g(); }
void g() { }
g
has not been declared before its first use. To fix it, either move the definition of g
before f
:
void g() { }
void f() { g(); }
Or add a declaration of g
before f
:
void g(); // declaration
void f() { g(); }
void g() { } // definition
This is Visual Studio-specific. In VS, you need to add #include "stdafx.h"
before any code. Code before it is ignored by the compiler, so if you have this:
#include <iostream>
#include "stdafx.h"
The #include <iostream>
would be ignored. You need to move it below:
#include "stdafx.h"
#include <iostream>
Feel free to edit this answer.
这篇关于什么是“未声明的标识符"错误,我该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!