访问另一个子类中的基类的受保护成员 [英] accessing a protected member of a base class in another subclass
问题描述
为什么要编译:
class FooBase
{
protected:
void fooBase(void);
};
class Foo : public FooBase
{
public:
void foo(Foo& fooBar)
{
fooBar.fooBase();
}
};
但不是?
class FooBase
{
protected:
void fooBase(void);
};
class Foo : public FooBase
{
public:
void foo(FooBase& fooBar)
{
fooBar.fooBase();
}
};
一方面,C ++授予对该类的所有实例的private / protected成员的访问权,另一方面它不允许访问子类的所有实例的基类的受保护成员。
这看起来与我不一致。
On the one hand C++ grants access to private/protected members for all instances of that class, but on the other hand it does not grant access to protected members of a base class for all instances of a subclass. This looks rather inconsistent to me.
我已经测试了编译VC ++和ideone.com,并编译第一个但不是第二个代码片段。 / p>
I have tested compiling with VC++ and with ideone.com and both compile the first but not the second code snippet.
推荐答案
当 foo
收到 FooBase
引用,编译器不知道参数是否是
Foo
的后代,因此它必须假设它不是。 Foo
可以访问继承的其他 Foo
对象的受保护成员,而不是所有其他同级类。
When foo
receives a FooBase
reference, the compiler doesn't know whether the argument is a descendant of Foo
, so it has to assume it's not. Foo
has access to inherited protected members of other Foo
objects, not all other sibling classes.
请考虑这个代码:
class FooSibling: public FooBase { };
FooSibling sib;
Foo f;
f.foo(sib); // calls sib.fooBase()!?
如果 Foo :: foo
成员任意 FooBase
后代,那么它可以调用 FooSibling
的protected方法,它与 Foo
。
If Foo::foo
can call protected members of arbitrary FooBase
descendants, then it can call the protected method of FooSibling
, which has no direct relationship to Foo
. That's not how protected access is supposed to work.
如果 Foo
需要访问受保护的所有成员 FooBase
对象,而不只是那些已知为 Foo
后代,然后 Foo
需要是 FooBase
的朋友:
If Foo
needs access to protected members of all FooBase
objects, not just those that are also known to be Foo
descendants, then Foo
needs to be a friend of FooBase
:
class FooBase
{
protected:
void fooBase(void);
friend class Foo;
};
这篇关于访问另一个子类中的基类的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!