我对C ++的私有继承有疑问。请参见以下代码示例:
#include <iostream>
class Foo {
public:
virtual void doSomething(int value) {
std::cout << value << std::endl;
}
};
void foobar(Foo& foo, int value) {
foo.doSomething(value);
}
class Bar : Foo {
public:
Bar() {
foobar(*this, 42); // <--- is OK despite private inheritance
}
};
int main() {
Bar b;
foobar(b, 42); // <--- is NOT OK because of private inheritance
}
Run Code Online (Sandbox Code Playgroud)
目前,我无法理解(或找到正确的C ++规范)为何尽管有私有继承foobar也可以在Bar的构造函数中调用该函数。如果我尝试调用函数对象的函数,编译器为如预期,因为私有继承的错误。*this foobarBarbmain
foobar(*this, 42)和foobar(b, 42)我忽略的地方有什么区别?
foobar这一切都来自于接收 a的事实,并且不知道(私下)继承自 的Foo事实。这个特征由调用者处理:BarFoo
Bar,为了调用foobarwith *this,需要进行转换;具体来说,*thisof 类型Bar需要转换为Foo&,这是可能的,因为调用者知道两种类型之间的继承关系。main(),在class Bar 范围之外,对foobarwith bwhich is 类型的调用Bar也需要转换。Bar但在这种情况下,和 之间的关系Foo是未知的,并且不可能进行转换。私有继承意味着只有派生类型知道此继承。在其范围内,一切都像公共继承一样发生。但在派生类型的范围之外,这种关系是未知的,一切的发生就好像根本没有继承一样。