我正在使用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;
}
这是我第一次使用头文件,很抱歉,如果我的错误非常明显。感谢您提前提供任何帮助。
答案 0 :(得分:2)
您没有检查相同的变量。
在
SDL_Surface *MenuBackground = LoadImage("Resources/Images/MenuBackground.png");
<{1}}中的行声明了一个名为CheckFiles()
的本地变量。此变量与程序中任何其他位置的任何其他同名变量无关(除了行所在的范围以及任何子范围)。