gpt4 book ai didi

C++:也许你知道这个陷阱?

转载 作者:行者123 更新时间:2023-11-27 23:33:28 25 4
gpt4 key购买 nike

我正在开发一款游戏。我有一个带有两个变量的 header GameSystem(只是像游戏循环这样的方法,没有类):
int mouseXint mouseY。这些在我的游戏循环中更新。现在我想从 Game.cpp 文件(一个由头文件和源文件构建的类)访问它们。所以,我在 Game.h#include "GameSystem.h"。这样做之后我得到了很多编译错误。当我删除包含时,他当然会说:

Game.cpp:33: error: ‘mouseX’ was not declared in this scope
Game.cpp:34: error: ‘mouseY’ was not declared in this scope

我想访问 mouseXmouseY 的地方。

我所有的 .h 文件都有由 Eclipse 生成的 Header Guards。
我正在使用 SDL,如果我删除想要访问变量的行,一切都会编译并完美运行 (*)。

我希望你能帮助我...

这是我 #include "GameSystem.h" 时的错误日志(他引用的所有代码都有效,如 (*) 所解释):

In file included from ../trunk/source/domein/Game.h:14,                 from ../trunk/source/domein/Game.cpp:8:../trunk/source/domein/GameSystem.h:30: error: expected constructor, destructor, or type conversion before ‘*’ token../trunk/source/domein/GameSystem.h:46: error: variable or field ‘InitGame’ declared void../trunk/source/domein/GameSystem.h:46: error: ‘Game’ was not declared in this scope../trunk/source/domein/GameSystem.h:46: error: ‘g’ was not declared in this scope../trunk/source/domein/GameSystem.h:46: error: expected primary-expression before ‘char’../trunk/source/domein/GameSystem.h:46: error: expected primary-expression before ‘bool’../trunk/source/domein/FPS.h:46: warning: ‘void FPS_SleepMilliseconds(int)’ defined but not used

This is the code which try to access the two variables:

SDL_Rect pointer;
pointer.x = mouseX;
pointer.y = mouseY;
pointer.w = 3;
pointer.h = 3;
SDL_FillRect(buffer, &pointer, 0xFF0000);

最佳答案

在您的 GameSystem header 中,不要将这些变量定义为:

int mouseX;
int mouseY;

相反,您应该声明它们:

extern int mouseX;
extern int mouseY;

然后在您的一个 .cpp 文件中定义它们:

int mouseX;
int mouseY;

在头文件中定义它们的问题在于,编译器将尝试在包含头文件的每个 .cpp 中实例化它们。

关于C++:也许你知道这个陷阱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3064237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com