2017-03-09 78 views
0

當我試圖從我的基類繼承我的sf :: Sprite和sf :: Texture到我的子類時,我似乎遇到了問題。當我嘗試發送精靈和紋理作爲副本時,這種方法很有用,但我當然不會獲得任何圖像。你有什麼想法如何解決這個問題?我的基類:試圖使用SFML中的精靈和紋理繼承

#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); 
} 

回答

2

你可以只標記那些成員protected而非private,讓您的派生類直接訪問它們:

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

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

是有效。謝謝!我不敢相信這很容易。我一直坐着,現在已經很長一段時間從const和call值切換。我沒有把保護作爲一種選擇。 – Henke