有没有一种技术可以使虚函数在所有派生类中强制重写?

Is there a technique to make a virtual function mandatory to override in all derived classes?

本文关键字:派生 重写 函数 一种 可以使 技术 有没有      更新时间:2023-10-16

考虑一下:

struct Base {
virtual void fn() = 0;
};
struct A: Base {
virtual void fn();
};
struct B: A {
// fn is not overridden here
};

基本上,fn是在A中实现的。B派生自AB不会覆盖fn

我希望有技术使B必须覆盖fn,因为如果不覆盖,这是一个错误。

可以这样做吗?编译时错误(或警告)是最好的,但如果不可能,那么运行时错误也是可以的。我只想知道,如果有人忘记在派生类中重写fn

这是什么原因呢?fn可以返回与类相关的信息。例如,它可以返回类名。或者它可以返回对象使用的分配空间量(用于调试目的)。或者执行一些与类相关的任务(例如,加载/保存其状态)。

如果fn未在B中被覆盖,则无法强制编译器生成错误。

您可以稍微修改一下代码以获得所需的内容。

  1. 使A::fn成为纯虚拟。将实现保留为A中的原样。请记住,即使它被声明为纯虚拟,实现A::fn也是完全可以的。

  2. 这将迫使您覆盖fnB.B::fn的实施可以根据需要利用尽可能多的A::fn


truct Base {
virtual void fn() = 0;
};
struct A : Base {
virtual void fn() = 0;
};
void A::fn()
{
// Add implmentation details
}
struct B : A {
// fn must be  overridden here
virtual void fn();
};
void B::fn()
{
A::fn();
// Add additonal logic for B
}

但是,如果A::fn称为 onB对象,则可能会生成运行时错误。

这里有一种方法可以做到这一点。

#include <iostream>
struct Base
{
virtual void fn() = 0;
virtual int getTypeID() = 0;
protected:
static int getNextID()
{
static int nextid = 0;
return ++nextid;
}
static int getClassTypeID()
{
static int id = getNextID();
return id;
}
};
struct A : Base 
{
virtual void fn();
virtual int getTypeID()
{
return getClassTypeID();
}
private:
static int getClassTypeID()
{
static int id = getNextID();
return id;
}
};
void A::fn()
{
if ( this->getTypeID() != A::getClassTypeID()  )
{
// Problem.
std::cout << "ERROR. fn() called on a derived class object.n";
}
else
{
std::cout << "OK. fn() called on an A object.n";
}
}
struct B : A
{
virtual int getTypeID()
{
return getClassTypeID();
}
static int getClassTypeID()
{
static int id = getNextID();
return id;
}
};
int main()
{
A* a1Ptr = new A;
A* a2Ptr = new B;
a1Ptr->fn();
a2Ptr->fn();
}

输出:

OK. fn() called on an A object.
ERROR. fn() called on a derived class object.