[英]Error: "this declaration has no storage class or type specifier" in c++
我正在嘗試編寫一些代碼,使我更容易制作 SDL 程序,因為我正在學習並經常開始新項目。 它基本上需要完成所有標准的 SDL 工作。 這是代碼
namespace engine {
class Engine
{
private:
SDL_Renderer* renderer;
SDL_Window* window;
SDL_Event event;
bool initialised = true;
bool quit = false;
public:
Engine(const char* name, int x, int y, int w = SDL_WINDOWPOS_CENTERED, int h = SDL_WINDOWPOS_CENTERED, bool fullscreen = false)
{
window = SDL_CreateWindow(name, x, y, w, h, fullscreen);
if (window == nullptr)
initialised = false;
renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer == nullptr)
initialised = false;
}
~Engine()
{
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
}
void handleEvents()
{
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
quit = true;
}
}
}
virtual void update()
{
}
virtual void render()
{
}
void start()
{
if (initialised && !quit)
{
handleEvents();
update();
render();
}
}
};
}
然后從這個繼承來制作一個游戲類
class Game : public engine::Engine
{
private:
engine::Engine game{"engine", 1200, 600};
public:
game.update() override
{
}
game.render() override
{
}
};
主要是這樣的
int main(int argc, char* argv[])
{
Game game();
game.start();
return 0;
}
但是我收到了標題中指定的錯誤engine::Engine game{"engine", 1200, 600};
在Game
課上。 我不知道我正在做的事情是否可行或如何去做。 謝謝你的幫助
我的目標:我想要一些代碼,就像一個可以在不同 SDL 項目中重用的庫。 這個引擎將是一個單獨的庫。 所以我想要某種從我的項目中的引擎繼承的引擎類。 說繼承表單引擎的類是game
。 我希望游戲覆蓋更新和渲染,以便我可以從渲染函數調用引擎中定義的不同繪圖方法。 這樣我每次啟動項目時都不必為事件制作窗口、渲染器和句柄。 我不知道這是否是一個好方法,但歡迎任何更好的解決方案。
我正在刪除Engine
以使示例更小。 我們不需要類中的任何 SDL 內容來展示如何解決這個問題。 除此之外, Engine
看起來還不錯。 不需要改變任何東西。
namespace engine {
class Engine
{
private:
bool initialised = true;
bool quit = false;
public:
Engine(const char* , int , int ) // simplified to remove the SDL stuff
{
}
~Engine() // may want this to be virtual. See link about virtual destructors
{
}
void handleEvents()
{
}
virtual void update()
{
}
virtual void render()
{
}
void start()
{
if (initialised && !quit)
{
handleEvents();
update();
render();
}
}
};
}
事情開始出錯的地方是嘗試實現Engine
。 我將在進行更改時內聯評論。
class Game : public engine::Engine // correct
{
// engine::Engine game{"engine", 1200, 600};
// don't need an engine::Engine as a member. Game IS an Engine.
public:
Game ():
engine::Engine {"engine", 1200, 600} // initialize base class here
{
}
// game.update() override
void update() override // use a normal function definition
// Compiler will figure out the rest
{
}
// game.render() override
void render() override // same as above
{
}
};
main
有一個小錯誤。 該語言有一個小怪癖,其中TYPE name()
看起來像一個函數,而不是一個變量。 這在 C++11 中得到了清理,添加了{}
以進行更一般的初始化1 。
int main()
{
// Game game(); declares a function, game, that returns a Game.
Game game; // defines a variable named game that is a Game. Could also be Game game{};
// note the different braces.
game.start();
return 0;
}
1將它與容器類一起使用時要小心。 vector<int> test{5};
是一個vector
,其中一個元素包含五個,而不是包含從vector<int> test(5);
獲得的默認零的五個元素vector<int> test(5);
.
一些補充閱讀:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.