考虑以下片段:
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.
这篇关于更改派生类中的函数访问模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!