C++ 上有点生锈了。类继承
子类访问受保护成员对象的规则是什么?我以为我理解了它们,但我的代码不同意。
我有一个基类,定义为
class Datum {
public:
Datum(Datum *r, Datum *l) : right(r), left(l) {}
protected:
Datum *right, *left;
};
我的 Datum 子类,如下所示:
class Column: public Datum
{
public:
Column(Datum *r, Datum *l, string n, int s): Datum(r,l), name(n), size(s) {}
void cover() {
right->left = left;
left->right = right;
}
protected:
string name;
int size;
};
当我使用 G++ v.4.5.1 进行编译时,我收到指向 cover 中的两行的错误消息:
error: Datum* Datum::right is protected
error: within this context
error: Datum* Datum::left is protected
error: within this context
显然,使该部分公开会导致错误消失离开。当该部分受到保护时,为什么它们还在那里?
What are the rules for a subclass accessing protected member objects? I thought I understood them but my code disagrees.
I have a base class, defined as
class Datum {
public:
Datum(Datum *r, Datum *l) : right(r), left(l) {}
protected:
Datum *right, *left;
};
I subclass Datum as follows:
class Column: public Datum
{
public:
Column(Datum *r, Datum *l, string n, int s): Datum(r,l), name(n), size(s) {}
void cover() {
right->left = left;
left->right = right;
}
protected:
string name;
int size;
};
When I compile, using G++ v.4.5.1, I get the error messages pointing to the two lines in cover:
error: Datum* Datum::right is protected
error: within this context
error: Datum* Datum::left is protected
error: within this context
Obviously, making the section public causes the errors to go away. Why are they there when the section is protected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是
Datum::Datum *right
受到保护。指针right
是可访问/可分配的,因为基类是公开继承的。但是right
指向的对象无法按照您在成员函数Column::cover()
中尝试的方式获得访问权限,因为right< 指向的对象/code> 与派生类的当前范围没有直接关系。
Datum::Datum *left
也存在类似的问题。The problem is
Datum::Datum *right
is protected. Pointerright
is accessible / assignable because the base class is inherited publicly. But the object pointed byright
has no access previliges the way you are trying to in the member functionColumn::cover()
because the object pointed byright
has no direct relation in the current scope of the derived class.Similar is the problem for the
Datum::Datum *left
too.当 Column 是另一个 Column 对象的成员时,Column 可以访问右侧和左侧,但当它们是任意 Datum 对象的成员时,则不能访问。
Column gets access to right and left when they are members of another Column object, but not when they are members of an arbitrary Datum object.