在派生类中更改函数访问模式 [英] Changing Function Access Mode in Derived Class

查看:165
本文介绍了在派生类中更改函数访问模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

  struct Base 
{
virtual〜Base

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

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

int main()
{
子child;

child.Foo(); //不会工作。 Foo在此上下文中是私有的。

static_cast< Base&> (child).Foo(); // 好的。 Foo在这方面是公开的。
}

这是合法的C ++吗?

解决方案

是的,改变派生类中的访问模式是 /en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface\">非虚拟接口成语。 此处提供了一些理由:

$ b $关键是虚拟函数存在以允许定制;除非它们还需要从派生类的代码中直接调用,否则不需要使它们为私有的。


为什么你实际上会在派生而不是 private 中在基础中创建 public ,但 private code>或 protected 继承不止我。


Consider the following snippet:

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.
}

Is this legal C++? "This" being changing the virtual function's access mode in the derived class.

解决方案

Yes, changing the access mode in derived classes is legal.

This is similar in form but different in intent to the Non-Virtual Interface idiom. Some rationale is given 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.

As to why you would actually make something public in base but private in derived without private or protected inheritance is beyond me.

这篇关于在派生类中更改函数访问模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆