抽象类C++

Obl*_*ion 1 c++ virtual sdl abstract

所以我的理解是,要在c ++中创建一个类抽象,你必须在该类中创建一个纯粹的虚拟方法.在我的代码中,我创建了一个抽象的GameObject类,它由我的Player类继承,但问题是我在我的Player.cpp中得到错误说错误LNK2001:未解析的extrenal符号"public:virtual void__thiscall GameObject :: Load(void)" (?加载@ GameObject @@ UAEXXZ)除了初始化之外的每个方法,当我将它们全部设置为0时,这会得到修复,我只是想知道为什么

// Abstract class to provide derived classes with common attributes

#include <SDL.h>
#include "AnimationManager.h"
#include "Debug.h"
#include "InputHandler.h"

class GameObject
{
public:
    virtual void Initialise() = 0;
    virtual void Load();
    virtual void HandleEvents();
    virtual void Update();
    virtual void Draw();
    Vector2D* position;
    int currantFrame;
    SDL_Renderer* renderer;
    float speed;
    bool alive;
};



#include "GameObject.h"

class Player : public GameObject
{
public:
    virtual void Initialise();
    virtual void Load();
    virtual void HandleEvents();
    virtual void Update();
    virtual void Draw();
    Player(SDL_Renderer* r);
    ~Player();
};



#include "Player.h"

Player::Player(SDL_Renderer* r)
{
    renderer = r;
}

Player::~Player()
{
}

void Player::Initialise()
{
    position = new Vector2D(10, 10);
    currantFrame = 0;
}

void Player::Load()
{
    TheAnimationManager::Instance()->load("Assets/circle.png", "player", renderer);
}

void Player::HandleEvents()
{
    SDL_Event event;

    if (SDL_PollEvent(&event))
    {
        switch(event.type)
        {
            case SDL_KEYDOWN:

                switch(event.key.keysym.sym)
                {
                    case SDLK_a:
                        DEBUG_MSG("A Pressed");
                        position->m_x -= 10;
                    break;

                    case SDLK_d:
                        DEBUG_MSG("D Pressed");
                        position->m_x += 10;
                    break;
                }

            break;
        }
    }
}

void Player::Update()
{
    Vector2D* p = TheInputHandler::Instance()->GetMousePosition();
    DEBUG_MSG(p->GetY());
    DEBUG_MSG(p->GetX());

    currantFrame = int(((SDL_GetTicks() / 100) % 4));
}

void Player::Draw()
{
    TheAnimationManager::Instance()->Animate("player", (int)position->GetX(), (int)position->GetY(), 90, 82, 0, currantFrame, renderer, SDL_FLIP_NONE);
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 5

可能通过非纯虚拟基类指针调用的每个虚拟方法都需要具有实现.

您似乎对抽象/虚拟的工作原理有一个倒退的想法.你不选择抽象课,为什么?您选择将成员函数设置为纯虚拟,因为它没有合理的实现.然后,由于具有纯虚函数,该类变为抽象.

变成抽象的类并不意味着它的每一个功能都突然变成纯粹的虚拟.

您的错误是链接器错误.链接器正在寻找GameObject::Load您未提供的函数的实现.如果将该函数标记为纯虚拟,则链接器将不会查找实现.

  • 不完全的.如果可以以某种方式调用,则只需要定义非`virtual`方法. (2认同)
  • @Jake:那是'Player`的实现.`GameObject`需要一个,除非你把它标记为纯虚拟. (2认同)