c++ - 什么是 'undeclared identifier' 错误,我该如何解决?

标签 c++ compiler-errors declaration undeclared-identifier

什么是未声明的标识符错误?常见原因有哪些?如何解决?

错误文本示例:

  • 对于 Visual Studio 编译器:error C2065: 'cout' : undeclared identifier
  • 对于 GCC 编译器:'cout' undeclared(在此函数中首次使用)

最佳答案

它们最常见的原因是忘记包含包含函数声明的头文件,例如,此程序将给出“未声明的标识符”错误:

缺少标题

int main() {
    std::cout << "Hello world!" << std::endl;
    return 0;
}

要修复它,我们必须包含标题:

#include <iostream>
int main() {
    std::cout << "Hello world!" << std::endl;
    return 0;
}

如果您编写了标题并正确包含它,则标题可能包含错误include guard .

要了解更多信息,请参阅 http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx .

变量拼写错误

当您拼错变量时,另一个常见的初学者错误来源:

int main() {
    int aComplicatedName;
    AComplicatedName = 1;  /* mind the uppercase A */
    return 0;
}

范围不正确

例如,此代码会出错,因为您需要使用 std::string :

#include <string>

int main() {
    std::string s1 = "Hello"; // Correct.
    string s2 = "world"; // WRONG - would give error.
}

在声明前使用

void f() { g(); }
void g() { }

g首次使用前未声明。要修复它,请移动 g 的定义之前 f :

void g() { }
void f() { g(); }

或添加 g 的声明之前 f :

void g(); // declaration
void f() { g(); }
void g() { } // definition

stdafx.h 不在顶部(VS 特定)

这是特定于 Visual Studio 的。在VS中,需要加上#include "stdafx.h"在任何代码之前。编译器忽略之前的代码,所以如果你有这个:

#include <iostream>
#include "stdafx.h"

#include <iostream>将被忽略。你需要把它移到下面:

#include "stdafx.h"
#include <iostream>

请随意编辑此答案。

关于c++ - 什么是 'undeclared identifier' 错误,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22197030/

相关文章:

java - java中变量的初始化和声明问题

java 在静态方法和主方法中处理变量声明和初始化

python - 如何确定变量是否在 Python 中声明?

c++ - sstream 不工作...(仍然)

compiler-errors - Algorand智能合约TEAL模板示例的编译错误

在 char* 数组中查找 char* 类型的 c++ 程序

c++ - 错误: variable or field 'functionName' declared void

java - 类不是抽象的并且不会覆盖抽象方法 AWT Program

c++ - 放置新的和析构函数

c# - 我如何在字符串变量中运行 ASM 操作码或将其转换为字节?