我正在尝试在我的游戏中为不同的屏幕创建一个状态引擎。 id开始屏幕,可能是未来的文件选择器,世界地图,菜单屏幕等。但是当我转发声明类时,它说没有构造函数。
GameState.h:
#pragma once
class GameState
{
public:
virtual ~GameState() {}
virtual void Update() {}
virtual void HandleEvents() {}
virtual void Draw(Graphics& gfx) {}
GameState* getCurrentState()
{
return currentState;
}
void ChangeState(GameState* state)
{
currentState = state;
}
protected:
SDL_Renderer* renderer;
GameState* currentState;
};
GameStates.h
#pragma once
#include "GameState.h"
#include "Texture.h"
#include "Keyboard.h"
class TitleGameState;
class IntroGameState : public GameState
{
public:
IntroGameState(SDL_Renderer* renderer, KeyboardClient& kbd)
:
kbd(kbd)
{
background = new Texture("red.png", renderer);
this->renderer = renderer;
}
~IntroGameState() {}
void HandleEvents()
{
while (!kbd.KeyEmpty())
{
KeyEvent e = kbd.ReadKey();
switch (e.GetCode())
{
case SDLK_RETURN:
if (e.IsPress())
{
currentState = new TitleGameState(renderer, kbd);
}
break;
}
}
}
void Logic() {}
void Draw(Graphics& gfx)
{
background->Draw(0, 0, gfx);
}
private:
Texture* background;
KeyboardClient& kbd;
};
class TitleGameState : public GameState
{
public:
TitleGameState(SDL_Renderer* renderer, KeyboardClient& kbd)
:
kbd(kbd)
{
background = new Texture("blue.png", renderer);
}
~TitleGameState() {}
void HandleEvents()
{
while (!kbd.KeyEmpty())
{
KeyEvent e = kbd.ReadKey();
switch (e.GetCode())
{
case SDLK_RETURN:
if (e.IsPress())
{
printf("OK");
}
break;
}
}
}
void Logic() {}
void Draw(Graphics&gfx)
{
background->Draw(0, 0, gfx);
}
private:
Texture* background;
KeyboardClient& kbd;
};
我之后定义了类,我知道我可以将它移到IntroGameState之上,但是当我实现菜单游戏状态时,它将在菜单状态和世界状态之间来回移动。我怎么能绕过这个?
编译器错误:
error C2514: 'TitleGameState' : class has no constructors File: gamestates.h Line: 28
第28行是这行代码:
currentState = new TitleGameState(renderer, kbd);
答案 0 :(得分:2)
行currentState = new TitleGameState(renderer, kbd);
上的错误是因为编译器还没有看到该类的构造函数。它不知道如何编译这段代码。
如果你转发声明类class TitleGameState;
,你可以声明的只是一个指针TitleGameState*
。
要编译您拥有的代码,您需要在使用之前定义该类。注意:定义类并不意味着定义所有方法。类定义由方法和成员声明组成。
class TitleGameState : public GameState
{
public:
TitleGameState(SDL_Renderer*, KeyboardClient&);
~TitleGameState();
void HandleEvents();
// ...
};
class IntroGameState : public GameState
{
// ...
}
在定义类之后,您可以定义成员函数;
/*inline*/ void TitleGameState::HandleEvents()
// inline is needed if the method is defined in a header file
// to help avoid linker errors
{
// ...
}