【问题标题】:Trying to make inheritance with sprites and textures in SFML尝试在 SFML 中使用精灵和纹理进行继承
【发布时间】:2017-07-30 06:45:17
【问题描述】:

当我试图将我的 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);
}

【问题讨论】:

    标签: c++ class inheritance sfml


    【解决方案1】:

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

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

    【讨论】:

    • 是的,它奏效了。谢谢!我不敢相信它是如此容易。很长一段时间以来,我一直坐着并从 const 和 call 值切换。我不认为受保护是一种选择。
    猜你喜欢
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 2016-06-11
    • 2023-03-19
    • 2017-05-19
    • 2012-05-09
    • 1970-01-01
    相关资源
    最近更新 更多