访问受保护的继承成员,带有指向基类的指针 [英] access protected inherited member with pointer to base class
问题描述
有人可以解释为什么此代码无效。
A类
{
public :
A(void){}
virtual〜A(void){}
protected:
A *
};
class B:public A
{
public:
B(void){parent = new B;}
〜B parent;}
protected:
int a;
};
class C:public B
{
public:
C(void){}
virtual〜C(void){}
void f(void){((B *)parent)→a; }
};
C
isn'能够访问 B
的成员
如果我转换 parent
到 C *
代替 B *
但我不希望用户承担任何不必要的风险。是否有更清洁的方法访问 a
?
谢谢。
B $>的受保护成员c $ c>,但只有当它们是 C
(也许你的,也许不是)的某个对象的一部分。换句话说,要从 C
访问 a
,您需要一个指针(或引用)到 C
。这是 protected
修饰符的含义。
这样做的原因如下。 ((B *)parent)
指针可能指向 B
的一些其他子类,完全不同于 C
,并且该子类可能具有 a
成员无法访问。
Can someone explain why this code doesn't work.
class A
{
public:
A(void){}
virtual ~A(void){}
protected:
A* parent;
};
class B : public A
{
public:
B(void){parent = new B;}
~B(void){delete parent;}
protected:
int a;
};
class C : public B
{
public:
C(void){}
virtual ~C(void){}
void f(void){ ((B*)parent)->a; }
};
How is it possible that C
isn't able to access members of B
?
If I convert parent
to a C*
in stead of a B*
it works fine. But I don't want users to take any unnecessary risks. Is there a cleaner way access a
?
Thanks.
解决方案 From an object of the C
class, you can access protected members of B
, but only if they're part of some object of class C
(maybe yours, maybe not). In other words, to access a
from C
, you need a pointer (or a reference) to C
. This is what the protected
modifier means.
The reason for this is the following. The ((B*)parent)
pointer may point to some other subclass of B
, completely different from C
, and that subclass may have the a
member inaccessible.
这篇关于访问受保护的继承成员,带有指向基类的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!