考虑以下代码段:
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”正在更改派生类中虚拟函数的访问模式。
最佳答案
是的,在派生类中更改访问模式是合法的。 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.
这是的形式,类似于,但的意图与Non-Virtual Interface惯用法不同。给出了一些理由here:
至于为什么您实际上会在基础中制作一些public
却在没有private
或private
继承的情况下派生出protected
超出我的范围。
关于c++ - 在派生类中更改功能访问模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63172351/