我正在学习 SDL,并正在尝试创建一个 GameObject
类,该类将成为我游戏中所有对象的基类。
这是头文件:
#pragma once
#include <stdio.h>
#include "Game.h"
#include "TextureManager.h"
class GameObject
{
public:
void load(int x, int y, int w, int h, std::string texture_id);
void draw(SDL_Renderer* renderer);
void update();
void clean() { printf("clean function.\n"); }
protected:
std::string texture_id;
int x;
int y;
int width;
int height;
int current_row;
int current_frame;
};
这是代码文件:
#include "GameObject.h"
void GameObject::load(int x, int y, int w, int h, std::string texture_id)
{
this->x = x;
this->y = y;
this->width = w;
this->height = h;
this->texture_id = texture_id;
this->current_row = 1;
this->current_frame = 1;
}
void GameObject::draw(SDL_Renderer *renderer)
{
TheTextureManager::Instance()->draw_frame(this->texture_id,
this->x, this->y, this->width, this->height,
this->current_row, this->current_frame, renderer);
}
void GameObject::update()
{
this->x += 1;
}
我正在尝试在 GameObject
类的私有部分创建 Player
类和 Game
(子类)的对象,以便使用 GameObject
函数(用于例如GameObject :: draw ()
)。
有代码:
#pragma once
#include <string>
#include <SDL2/SDL.h>
#include "GameObject.h"
#include "Player.h"
class Game
{
private:
SDL_Renderer* renderer;
SDL_Window* window;
GameObject game_object;
Player player;
bool running;
public:
Game() {}
~Game() {}
void init(std::string name, int x, int y, int width, int height, int flags = 0);
void update();
void handle_events();
void draw();
void clear();
bool is_running() { return running; }
};
但是当我声明这些行时,我收到以下错误:
g++ -std=c++11 -Wall -g -o obj/Game.o -c src/include/Game.cpp
g++ -std=c++11 -Wall -g -o obj/Player.o -c src/include/Player.cpp
In file included from src/include/GameObject.h:4,
from src/include/Player.h:3,
from src/include/Player.cpp:1:
src/include/Game.h:13:5: error: ‘GameObject’ does not name a type
13 | GameObject game_object;
| ^~~~~~~~~~
src/include/Game.h:14:5: error: ‘Player’ does not name a type
14 | Player player;
| ^~~~~~
make: *** [Makefile:47: obj/Player.o] Error 1
我使用 Makefile 实用程序来构建项目。请告诉我我的错误在哪里?为什么我不能创建和使用类对象?
附言这是 Player
类:
标题。
#pragma once
#include "GameObject.h"
class Player : public GameObject
{
public:
void load(int x, int y, int w, int h, std::string texture_id);
void draw(SDL_Renderer* renderer);
void update();
void clean() { GameObject::clean(); printf("clean a player.\n"); }
};
身体。
#include "Player.h"
void Player::load(int x, int y, int w, int h, std::string texture_id)
{
GameObject::load(x, y, w, h, texture_id);
}
void Player::draw(SDL_Renderer* renderer)
{
GameObject::draw(renderer);
}
void Player::update()
{
this->y += 1;
this->x -= 1;
}