我正在使用 SDL 在 C++ 中编写一个简单的游戏。我以前写过一个更复杂的游戏,但它在一个由 4000 多行代码组成的源文件中。
我的问题是变量似乎在它们定义的 .cpp 文件的末尾被重置。
在 Declarations.cpp 中(除其他外)
bool CheckFiles()
{
SDL_Surface *Background = LoadImage("Resources/Images/Background.png");
SDL_Surface *Character1 = LoadImage("Resources/Images/Character.png");
SDL_Surface *MenuBackground = LoadImage("Resources/Images/MenuBackground.png");
TTF_Font *EightBitLimit = TTF_OpenFont("Resources/Fonts/EightBitLimit.ttf",16);
TTF_Font *KarmaFuture = TTF_OpenFont("Resources/Fonts/KarmaFuture.ttf",16);
TTF_Font *EightBitLimitSmall = TTF_OpenFont("Resources/Fonts/EightBitLimit.ttf",9);
SDL_Surface *Message1 = NULL;
SDL_Surface *Message2 = NULL;
if (Background == NULL) return false;
if (Character1 == NULL) return false;
if (MenuBackground == NULL) return false;
if (EightBitLimit == NULL) return false;
if (KarmaFuture == NULL) return false;
if (EightBitLimitSmall == NULL) return false; //Breakpoint here, everything has loaded fine
return true;
}
在 Menu.cpp 中
#include"Declarations.h"
#include"Menu.h"
void Menu()
{
while (Quit == false && State == MENU)
{
CheckFiles();
ApplySurface(0,0,MenuBackground,Screen); //Gives an access violation as all surfaces and fonts have became NULL
Message1 = TTF_RenderText_Solid(KarmaFuture,"Tripping Octo Dangerzone",White);
我的头文件受到了适当的保护。变量和函数声明如下:
extern TTF_Font *KarmaFuture;
extern bool CheckFiles();
我的 main.cpp 文件:
#include"Declarations.h"
#include"Menu.h"
#include"Game.h"
int main (int argc, char* argv [])
{
if (Init() == false) return -1;
if (CheckFiles() == false) return -1; //Everything is initialized and loaded properly
while (Quit == false)
{
switch(State)
{
case MENU:
Menu();
break;
case GAME:
Game();
break;
}
}
return 0;
这是我第一次使用头文件,如果我的错误非常明显,我深表歉意。提前感谢您的帮助。
最佳答案
您检查的不是同一个变量。
SDL_Surface *MenuBackground = LoadImage("Resources/Images/MenuBackground.png");
CheckFiles()
中的行声明了一个名为MenuBackground
的本地 变量。此变量与程序中任何其他位置的任何其他同名变量无关(除了该行所在的范围和任何子范围)。
关于c++ - 在定义后包含时, header 中的值设置为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17487238/