为什么基指针只能在公共继承下指向派生对象?

g3n*_*air 8 c++ inheritance pointers

我认为它是因为基类数据成员和方法不可访问,但我想更清楚一点.另外,这是多态(使用虚函数)只能在公共继承下才可能的原因吗?

Rei*_*ica 13

实际上,即使基类是私有的,指向base的指针也可以指向派生类.问题是,这种转换是不可能从外面的类.但是,仍然可以在可访问基础的上下文中执行此类转换.

例:

#include <iostream>
using namespace std;

struct Base
{
    void foo() const {
        cout << "Base::foo()\n";
    }
};

struct Derived : private Base
{
    const Base* get() const {
        return this; // This is fine
    }
};

int main()
{
    Derived d;
    const Base *b = &d; // This is illegal
    const Base *b = d.get(); //This is fine
    b->foo();
}
Run Code Online (Sandbox Code Playgroud)

实例

虚拟呼叫的实例