尝试在SFML中使用sprite和纹理进行继承

时间:2017-03-09 10:22:05

标签: c++ class inheritance sfml

当我尝试从我的基类继承我的sf :: Sprite和sf :: Texture到我的子类时,我似乎遇到了问题。当我尝试将精灵和纹理作为副本发送时,它有点起作用,但我当然不会得到任何图像。你知道如何解决这个问题吗?我的基类:

#ifndef OBJECTHOLDER_H
#define OBJECTHOLDER_H
#include <SFML\Graphics.hpp>
using namespace std;

class ObjectHolder : public sf::Drawable {

private:
    float windowHeight;
    float windowWidth;
    sf::Texture texture;
    sf::Sprite sprite;
public:
    ObjectHolder();
    virtual ~ObjectHolder();
    float getWindowHeight() const;
    float getWindowWidth() const;
    const sf::Sprite & getSprite() const;
    const sf::Texture & getTexture() const;
};

#endif //OBJECTHOLDER_H

#include "ObjectHolder.h"

ObjectHolder::ObjectHolder() {
    float windowHeight;
    float windowWidth;
}

ObjectHolder::~ObjectHolder() {
}

float ObjectHolder::getWindowHeight() const {
    return this->windowHeight;
}

float ObjectHolder::getWindowWidth() const {
    return this->windowWidth;
}

const sf::Sprite & ObjectHolder::getSprite() const {
    return this->sprite;
}

const sf::Texture & ObjectHolder::getTexture() const {
    return this->texture;
}

我的子类:

#ifndef PROJECTILE_H
#define PROJECTILE_H
#include "ObjectHolder.h"

class Projectile : public ObjectHolder {
public:
    Projectile();
    virtual ~Projectile();
    void move(const sf::Vector2f& amount);
    virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};

#endif //PROJECTILE_H

#include "Projectile.h"
#include <iostream>

Projectile::Projectile() {
    if (!this->getTexture().loadFromFile("../Resources/projectile.png")) { 
        cout << "Error! Projectile sprite could not be loaded!" << endl;
    }
    this->getSprite().setTexture(getTexture());
    this->getSprite().setPosition(sf::Vector2f(940.0f, 965.0f));
}

Projectile::~Projectile() {
}

void Projectile::move(const sf::Vector2f & amount) {
    this->getSprite().move(amount);
}

void Projectile::draw(sf::RenderTarget & target, sf::RenderStates states) const{
    target.draw(this->getSprite(), states);
}

1 个答案:

答案 0 :(得分:2)

您可以将这些成员标记为protected而不是private,这样您的派生类就可以直接访问它们:

class Base {
protected:
    sf::Texture m_Texture;
}

class Derived : public Base {
    Derived() {
        m_Texture.loadFromFile("myTexture.png");
    }
}