Changing Function Access Mode in Derived Class(更改派生类中的函数访问模式)
问题描述
考虑以下片段:
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"正在改变派生类中虚函数的访问模式.
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.
这在形式上相似,但在意图上与不同/Non-Virtual_Interface" rel="noreferrer">非虚拟接口 习惯用法.此处给出了一些理由:
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.
至于为什么您实际上会在基础中制作public,而在没有private 或protected 的派生中制作private继承超出了我的范围.
As to why you would actually make something public in base but private in derived without private or protected inheritance is beyond me.
这篇关于更改派生类中的函数访问模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:更改派生类中的函数访问模式
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
