c++ - 在派生类中更改功能访问模式

标签 c++ inheritance access-modifiers

考虑以下代码段:

struct Base
{
  virtual ~Base() {}

  virtual void Foo() const = 0; // Public
};

class Child : public Base
{
  virtual void Foo() const {} // Private
};

int main()
{
  Child child;

  child.Foo(); // Won't work. Foo is private in this context.

  static_cast<Base&> (child).Foo(); // Okay. Foo is public in this context.
}

这是合法的C++吗? “This”正在更改派生类中虚拟函数的访问模式。

最佳答案

是的,在派生类中更改访问模式是合法的。

这是的形式,类似于,但的意图与Non-Virtual Interface惯用法不同。给出了一些理由here:

The point is that virtual functions exist to allow customization; unless they also need to be invoked directly from within derived classes' code, there's no need to ever make them anything but private.



至于为什么您实际上会在基础中制作一些public却在没有privateprivate继承的情况下派生出protected超出我的范围。

关于c++ - 在派生类中更改功能访问模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63172351/

相关文章:

c++ - 从 BST 的给定范围插入元素到数组中

c++ - Ping "no resources"- 是什么原因造成的?

c++ - 如何在我的冒泡排序中为字符串和 double 实现异常处理程序?

java - 在方法中返回类的实例

C++多重继承函数合并

c# - 实现接口(interface)扩展属性(继承?)

java - 访问修饰符 protected

c++ - 如何使用带有 future<T> vector 的基于范围的 for 循环

swift - swift 类的私有(private)访问控制行为是什么?

d - 我在哪里可以阅读更多关于 D 的类访问修饰符的信息?