【问题标题】:Error C2065 - Global Variable Used In Header File错误 C2065 - 头文件中使用的全局变量
【发布时间】:2015-01-02 01:08:41
【问题描述】:

我的 cpp 文件中有一个全局字符串变量,并在头文件中使用它,它给了我 C2065 错误,当我最后一次拥有这个项目并创建它工作的头文件时,我做了对任何一个文件都没有更改,并且它给了我全局变量的错误。在尝试使用 cpp 文件中声明的头文件中的全局函数时,它也给了我 C3861 错误,而它以前也可以工作。在我保存并关闭我的项目之前一切正常,但现在它根本不工作。

cpp 文件:

#include "stdafx.h"
#include "header.h"
#include <iostream>
#include <stdlib.h>
#include <string>
#include <windows.h>

using namespace std;

void story();       //--Function Declaration--
void tutorial();
void startGame();
void chooseClass();
void gameMenu();
void exitGame();    //--End Function Declaration--

string name;
string className;

头文件:

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

using namespace std;

void chooseClass(){
    className = "Warrior";

    gameMenu();
}

头文件使用className字符串变量,并进入gameMenu函数。头文件中的chooseClass函数可以正常工作。

错误:

header.h(32): error C2065: 'className' : undeclared identifier
header.h(35): error C3861: 'gameMenu': identifier not found

【问题讨论】:

  • 您可以从您的 .h 和 .cpp 文件中添加代码吗?至少是相关的部分。
  • 您的某个标题中可能有一个全局变量。这意味着包含该标头的每个编译单元都将具有相同的全局变量。您可能需要一个带有全局变量的 .cpp 文件,并通过在标头中使用“extern”声明该变量来将该变量导出到其他编译单元。
  • 我头文件里没有全局变量,只有cpp文件
  • 您的一些定义与它们应该是相反的,即函数的主体应该在 cpp 文件中而不是头文件中(头文件将只包含函数定义,而不是完整的功能体)。类变量应该在头部定义,void chooseClass()应该是void ::chooseClass()gameMenu 在 header.h 中引用的代码也丢失了,这使得该错误更难确定它发生的原因。
  • chooseClass 函数由于缺少分号和className 未声明而无法编译。

标签: c++


【解决方案1】:

在你的标题中写:

void chooseClass(const std::string& name);

this 声明了函数。

然后在您的 cpp 文件中实现该功能。

// the global variable
std::string className;

//set the global variable to a value.
chooseClass(const std::string& name)
{
    className = name;
}

然后在另一个 .cpp 文件中,您将使用 set 选择类函数,如 chooseClass("warrior");

然后作为旁注:您可能希望为您的游戏类使用枚举。

【讨论】:

    猜你喜欢
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多