我可以禁止从 base 调用 derived class 的私有成员吗?

Can I forbid calling private member of derived class from base?

我有这个代码:

struct A {
  virtual void f() {}
};
struct B: A {
 private:
  void f() override {}
};
...
B b;
A& a = b;
a.f();

当然它会从 B 调用 f() 因为在编译时检查了 private 但选择虚拟函数版本是在运行时。在这种情况下我可以禁止 f() 调用吗?

没有。当您在 A 引用上调用 f() 时,会在 A 上检查访问规则。您不能指望编译器检查 B 的规则,因为它不一定知道 aB.

类型

来自cppreference

Access rules for the names of virtual functions are checked at the call point using the type of the expression used to denote the object for which the member function is called. The access of the final overrider is ignored:

struct B { virtual int f(); }; // f is public in B
 
class D : public B { private: int f(); }; // f is private in D
 
void f() {
  D d;
  B& b = d;
  b.f(); // OK: B::f is public, D::f is invoked even though it's private
  d.f(); // error: D::f is private
}

尽管如此,您的代码不应依赖于此。在我看来,给定方法的访问说明符应该在 class 层次结构中保持一致。