gpt4 book ai didi

c++ - 为什么基指针只能在公共(public)继承下指向派生对象?

转载 作者:可可西里 更新时间:2023-11-01 18:17:26 26 4
gpt4 key购买 nike

我认为这是因为基类数据成员和方法将无法访问,但我想更清楚地了解这一点。另外,这是否就是多态性(使用虚函数)只有在公共(public)继承下才有可能的原因?

最佳答案

实际上,即使基类是私有(private)的,指向基类的指针也可以指向派生类。问题是这样的转换在课外是不可能的。但是,仍然可以在可访问基础的上下文中执行此类转换。

例子:

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

Live example

Live example with virtual call

关于c++ - 为什么基指针只能在公共(public)继承下指向派生对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16666317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com