可能重复:
C++:覆盖公共\私有继承
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 child;
b->doSomething(); // Calls the derived class function even though that is private
问题:
- 即使它是私有的,它也能够调用派生类函数。这怎么可能?
现在,如果我将继承访问说明符从 public 更改为 protected/private,则会出现编译错误:
'type cast' : conversion from 'Derived *' to 'base *' exists, but is inaccessible
注意:我知道继承访问说明符的概念。因此,在第二种情况下,由于它是私有/受保护的,因此无法访问。但我想知道第一个问题的答案。任何输入将不胜感激。