为什么基指针只能在公共继承下指向派生对象? [英] why can a base pointer point to derived object only under public inheritance?

查看:102
本文介绍了为什么基指针只能在公共继承下指向派生对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为是这样,因为基类的数据成员和方法将不可访问,但是我希望对此更加清楚.另外,这就是为什么仅在公共继承下才可以使用多态(使用虚拟函数)的原因吗?

I think its because the base class data members and methods wont be accessible , but I'd like some more clarity on this. Also, is this the reason why polymorphism (using virtual functions) is possible only under public inheritance?

推荐答案

实际上,即使基数是私有的,指向基数的指针也可以指向派生类.问题是,从类之外进行这种转换是不可能的.但是,仍然可以在可访问基础的情况下进行这种转换.

Actually, a pointer to base can point to a derived class even if the base is private. The thing is that such a conversion is impossible from outside the class. However, it's still possible to perfrom such a conversion in a context where the base is accessible.

示例:

#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();
}

在线示例

带有虚拟呼叫的实时示例

这篇关于为什么基指针只能在公共继承下指向派生对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆