[英]Visibility of private virtual function in abstract base classes
Consider following code:考虑以下代码:
class A {
public:
virtual void f() const = 0;
void callf() const { f(); }
};
class B : public A {
virtual void f() const { }
};
int main()
{
B x;
x.callf();
return 0;
}
Class B
derives from the abstract base class A
, but "hides" the implemented method f()
as private member.类
B
派生自抽象基类A
,但“隐藏”了已实现的方法f()
作为私有成员。 Still, the inherited member callf()
is able to call f()
, which was public in the base class.尽管如此,继承的成员
callf()
能够调用f()
,它在基类中是公共的。 The code compiles with no warning on g++ 10.1.0 and clang++ 11.1.0.代码在 g++ 10.1.0 和 clang++ 11.1.0 上编译时没有警告。
Is this a legal code, ie, does the inherited callf()
correctly see the private member f()
?这是一个合法的代码,即继承的
callf()
是否正确地看到了私有成员f()
?
Alternatively, would it be possible for the derived class B
to implement the purely virtual methods of the base class, such that they can only be called by B
(and friends)?或者,派生类
B
是否有可能实现基类的纯虚方法,以便它们只能由B
(和朋友)调用?
Is this a legal code, ie, does the inherited callf() correctly see the private member f()?
这是一个合法的代码,即继承的 callf() 是否正确地看到了私有成员 f()?
Yes, it is legal code.是的,这是合法的代码。 From the compiler's point-of-view, the
callf
function is referencing the f
function of its own class;从编译器的角度来看,
callf
函数引用了它自己类的f
函数; the fact that that is a virtual function does not affect the scope (or accessibility) – only the implementation, which will be in the form of a call to a v-table entry.这是一个虚函数这一事实不影响范围(或可访问性)——仅影响实现,它将以调用 v-table 条目的形式出现。 That v-table entry will be correctly interpreted at run time, when it is called via the derived class.
当通过派生类调用时,该 v-table 条目将在运行时被正确解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.