c++ - 派生类中的私有重写虚函数
问题描述
如果这些在基类中是公共的,那么从基类私有覆盖的虚拟成员函数是否有任何意义?
struct base {
virtual void a();
};
struct derived : base {
// ...
private:
void a() override;
};
解决方案
查看您的设计,我发现无法derived::a
直接调用,而只能通过base
接口调用。
有什么意义吗?考虑一下,一旦我们有了一个derived
实例,我们总是可以向上转换到它的基础,所以给定
derived d;
虽然d.a()
不会编译,但我们总是可以做
base & b = d;
b.a(); //which actually calls derived::a
换句话说:毕竟derived::a
不是那么私密,我不鼓励这种设计,这可能会让用户感到困惑。
如果成员 private inderived
也是 private in base
,情况就会发生变化:这一次很明显,它们不能直接在外部base
或中调用derived
。
假设我们有几个函数,并希望根据作为参数传递给第三个函数的值有条件地调用它们:
struct base
{
void dosomething(bool x)
{
if(x)
{
do_this();
}
else
{
do_that();
}
}
private:
virtual void do_this(){}
virtual void do_that(){}
};
因此派生类可能是这样的:
struct derived : base
{
private:
void do_this() override { }
void do_that() override { }
};
并且没有其他类可以调用它们,除非它扩展了base
自己:
derived d;
d.dosomething(true); //will call do_this() in derived
d.dosomething(false); //will call do_that() in derived
d.do_that() //won't compile
推荐阅读
- form-submit - oTree 中的非提交按钮
- javascript - 未捕获的引用错误:未定义 openCity()
- php - PHP7.0 会话处理程序问题(权限被拒绝且函数表已损坏)
- sql - PostgresSQL:json键的触发器比较
- reactjs - Npm run build 失败,抛出错误代码 ELIFECYCLE
- laravel - 如何使用 laravel 集合从数据库中获取 Laravel 表单中下拉列表的数据?
- postgresql - 将数组与postgres中的数组列进行比较
- c# - 重用 Azure Function 中的作用域 ILogger 实例
- r - Jupyter-Notebooks 卡在“内核启动,请稍候”(R 内核)
- mysql - SQL 查询,获取一个实体的多个日期