[英]Interaction Between Interface Implementation and Private Inheritance
When a class is inherited privately, all members of that class become private in the child class. 当某个类被私有继承时,该类的所有成员在子类中将变为私有。 However, in the following example, we are able to indirectly access the privately inherited doWork function implementation through AD (pointed to using a pointer to R type).
但是,在下面的示例中,我们能够通过AD(指向使用R类型的指针)间接访问私有继承的doWork函数实现。
How is this allowed? 如何允许? Does virtual lookup ignore visibility rules since it is done at runtime?
虚拟查找是否在运行时完成,会忽略可见性规则?
#include <iostream>
using std::cout;
class R
{
public:
virtual void doWork() = 0;
};
class RA : public virtual R
{
public:
void doWork() { cout << "RA doWork\n"; };
};
class P : public virtual R, private RA
{
public:
P() : RA() {};
};
class AD : public virtual R, private P
{
public:
AD() : P() {};
void doWork(int k) { cout << "AD Time dowork " << k << "\n";}
};
int main()
{
AD ad;
R* p = &ad;
p->doWork();
}
The above code will print "RA doWork" when run. 上面的代码在运行时将打印“ RA doWork”。 My expectation was that it would result in a runtime error, because doWork's definition would not be accessible from p due to the private inheritance.
我的期望是会导致运行时错误,因为由于私有继承,无法从p访问doWork的定义。
AD
inherits privately from P
but publicly from R
. AD
从P
私有继承,但从R
公开继承。 What this means in practice is that public methods declared in R
will still be accessible in AD
but public methods declared in P
but not in R
will not be accessible in AD
. 实际上,这意味着在
R
声明的公共方法仍然可以在AD
访问,但是在P
声明但在R
声明的公共方法将无法在AD
访问。 So for example if P
looked like: 例如,如果
P
看起来像:
class P : public virtual R, private RA
{
public:
P() : RA() {};
void doWorkP() { std::cout << "doWorkP" << std::endl; }
};
You would be able to access doWork
through AD
but not doWorkP
. 您将可以通过
AD
访问doWork
,但不能访问doWorkP
。
If you want to make R
's methods inaccessible in AD
simply inherit from R
privately. 如果要使
R
的方法在AD
不可访问,只需从R
私有继承即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.