我有一个基于SFML gamefromscratch.com教程的类,称为"VisibleGameObject"在这个类中,是一个私有变量"_sprite",以及一个"getSprite()"函数,我尝试作为保护和公共。(即使作为公共函数,它仍然说"_sprite"是私有的,即使公共函数返回变量)。
在我的OnRender类中,我创建了两个VisibleGameObjects。
VisibleGameObject _testtile1;
VisibleGameObject _cursorSprite;
但是当我绘制精灵时,我得到了错误:within this context.
_mainWindow.draw(_cursorSprite._sprite);
或者我尝试(与getSprite()被保护或公共)。
_mainWindow.draw(_cursorSprite.getSprite());
然而,"error: 'sf::Sprite VisibleGameObject::_sprite'总是私有的。错误:within this context"
对我来说没有任何意义,因为
1) _sprite是VisibleGameObject的一个变量。它可能是私有的,但除了它自己的原始类"VisibleGameObject"之外,它不能被任何东西访问。我认为类可以访问自己的变量,即使它们是另一个类中的新实例化对象?
2) getSprite()是公共的,并返回私有变量,但它仍然说_sprite是私有的?这对我来说毫无意义!我学到的关于Getter和setter的所有知识都表明,公共函数可以返回私有变量,因为这就是Getter的全部意义。
sf::Sprite& VisibleGameObject::getSprite()
{
return _sprite;
}
class VisibleGameObject
{
public:
VisibleGameObject();
virtual ~VisibleGameObject();
private:
sf::Sprite _sprite;
protected:
sf::Sprite& getSprite();
或
public:
sf::Sprite& getSprite();
类的受保护成员只能被类本身和从它派生的类访问。
因为你调用绘制函数不是从类中派生自VisibleGameObject你得到一个错误。
你可能应该看看这个:http://www.cplusplus.com/doc/tutorial/inheritance/