gpt4 book ai didi

c++ - 派生类中的私有(private)虚函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:14:35 27 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
C++: overriding public\private inheritance

class base {
public:
virtual void doSomething() = 0;
};

class derived : public base {
private: // <-- Note this is private

virtual void doSomething()
{ cout << "Derived fn" << endl; }
};

现在,如果我执行以下操作:

base *b = new derived;
b->doSomething(); // Calls the derived class function even though that is private

问题:

  1. 它能够调用派生类函数,即使它是私有(private)的。这怎么可能?

现在,如果我将继承访问说明符从 public 更改为 protected/private,我会收到一个编译错误:

'type cast' : conversion from 'derived *' to 'base *' exists, but is inaccessible

注意:我知道继承访问说明符的概念。所以在第二种情况下,因为它是私有(private)的/ protected ,所以它是不可访问的。但我想知道第一个问题的答案。任何输入将不胜感激。

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