这在 Java 中是不允许的:
class A {
public void method() {}
}
class B extends A {
private void method() {}
}
它会产生一个编译错误:
error: method() in B cannot override method() in A
attempting to assign weaker access privileges; was public
但是,这在 C++ 中是允许的:
class A {
public:
virtual void method() {}
};
class B : public A {
private:
void method() {}
};
int main(void) {
A* obj = new B();
obj->method(); // B::method is invoked, despite it being private
}
C++ 中这种行为背后的逻辑是什么?