C++ 私有/受保护变量“;错误:在此上下文中;
我有一个基于SFML gamefromscratch.com教程的类,在这个类中称为“VisibleGameObject”,它是一个私有变量“\u sprite”,也是一个“getSprite()”函数,我尝试将其作为受保护函数和公共函数。(即使是public,它仍然表示“_sprite”是私有的,即使public函数返回变量) 在OnRender类中,我创建了两个VisibleGameObjectsC++ 私有/受保护变量“;错误:在此上下文中;,c++,function,inheritance,private,public,C++,Function,Inheritance,Private,Public,我有一个基于SFML gamefromscratch.com教程的类,在这个类中称为“VisibleGameObject”,它是一个私有变量“\u sprite”,也是一个“getSprite()”函数,我尝试将其作为受保护函数和公共函数。(即使是public,它仍然表示“_sprite”是私有的,即使public函数返回变量) 在OnRender类中,我创建了两个VisibleGameObjects VisibleGameObject _testtile1; VisibleGameObject
VisibleGameObject _testtile1;
VisibleGameObject _cursorSprite;
但是当我绘制精灵时,我得到了一个错误:在这个上下文中
_mainWindow.draw(_cursorSprite._sprite);
或者我尝试过(getSprite()被保护或公开)
但始终,“错误:'sf::Sprite VisibleGameObject::Sprite'是私有的。错误:在此上下文中”
对我来说没有任何意义,因为
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();
或
类的受保护成员只能由类本身及其派生的类访问 由于不是从VisibleGameObject派生的类中调用draw函数,因此会出现错误 您可能应该阅读以下内容:
好的。。。有时我认为我的编译器有缺陷。我刚刚尝试将getSprite()公开,现在它起作用了。但仍然不能起到保护作用,或者使精灵受到保护。我仍然不明白为什么sprite不能被它自己的对象类访问。
sf::Sprite& VisibleGameObject::getSprite()
{
return _sprite;
}
class VisibleGameObject
{
public:
VisibleGameObject();
virtual ~VisibleGameObject();
private:
sf::Sprite _sprite;
protected:
sf::Sprite& getSprite();
public:
sf::Sprite& getSprite();