[英]Unable to access protected member from derived class
I have a setup something along the lines of this. 我有一些类似的设置。 Multiple levels of inheritance from a single base class containing a protected member x.
从包含受保护成员x的单个基类继承的多个级别。
class Sprite {
protected:
float x, y;
}
class AnimatedSprite : Sprite {
public:
void draw(float x, float y);
}
class Player : AnimatedSprite {
public:
void draw(float x, float y);
}
The implementation for the method draw in derived class Player is something along these lines. 在派生类Player中,方法draw的实现与此类似。
void Player::draw(float x, float y) {
AnimatedSprite::draw(this->x, this->y);
}
However compiler is complaining that members x and y are inaccessible, even though they are listed as protected in the base class. 但是,编译器抱怨成员x和y不可访问,即使它们在基类中被列为受保护的也是如此。
Derivation for a class
is private
by default. 默认情况下,派生
class
是private
的。 If you want to access the protected
base members, then you must make the derivation public
: 如果要访问
protected
基本成员,则必须将派生public
:
class AnimatedSprite : public Sprite
// ...
class Player : public Sprite
(You could also make the derivation protected
, but that would be a rather exotic thing to do. You could likewise make the first derivation public
or protected
and leave the second one private
, but that would not match the supposed intention of the class hierarchy. public
inheritance is clearly what you are looking for in both cases.) (您也可以使派生成为
protected
,但这将是一件非常奇怪的事情。您也可以将第一个派生public
或protected
而将第二个派生保留为private
,但这与类层次结构的预期目的不符。在这两种情况下,您显然都希望找到public
继承。)
AnimatedSprite
uses private inheritance, so the members of Sprite
become private members of AnimatedSprite
. AnimatedSprite
使用私有继承,因此Sprite
的成员成为AnimatedSprite
私有成员。 You might want to use protected inheritance: 您可能要使用受保护的继承:
class AnimatedSprite : protected Sprite {
public:
void draw(float x, float y);
}
class Player : protected AnimatedSprite {
public:
void draw(float x, float y);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.