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.
这篇关于更改派生类中的函数访问模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:更改派生类中的函数访问模式
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
