gpt4 book ai didi

c++ - C++中公共(public)继承基类调用派生类的私有(private)虚函数

转载 作者:行者123 更新时间:2023-11-28 05:38:27 24 4
gpt4 key购买 nike

我的代码:

#include <iostream>
using namespace std;
class Base
{
public:
void print() { doPrint();}
private:
virtual void doPrint() {cout << "Base::doPrint" << endl;}
};

class Derived : public Base
{
private:
virtual void doPrint() {cout << "Derived::doPrint" << endl;}
};

int main()
{
Derived *d = new Derived();
Base* p = dynamic_cast<Base*>(d);
p->print();
delete d;
return 0;
}

输出是Derived::doPrint,我不太清楚答案。为什么不是 Base::doPrint?公有继承下,为什么Base类可以调用Derived类的私有(private)虚函数?

最佳答案

在 C++ 中,访问检查是在表达式的静态(编译时)类型上完成的,但虚拟调用使用动态(运行时)类型。

在您的示例中,*p 具有静态类型 Base 和动态类型 Derived

关于c++ - C++中公共(public)继承基类调用派生类的私有(private)虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37706127/

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