有没有一种技术可以使虚函数在所有派生类中强制重写?
Is there a technique to make a virtual function mandatory to override in all derived classes?
考虑一下:
struct Base {
virtual void fn() = 0;
};
struct A: Base {
virtual void fn();
};
struct B: A {
// fn is not overridden here
};
基本上,fn
是在A
中实现的。B
派生自A
,B
不会覆盖fn
。
我希望有技术使B
必须覆盖fn
,因为如果不覆盖,这是一个错误。
可以这样做吗?编译时错误(或警告)是最好的,但如果不可能,那么运行时错误也是可以的。我只想知道,如果有人忘记在派生类中重写fn
。
这是什么原因呢?fn
可以返回与类相关的信息。例如,它可以返回类名。或者它可以返回对象使用的分配空间量(用于调试目的)。或者执行一些与类相关的任务(例如,加载/保存其状态)。
如果fn
未在B
中被覆盖,则无法强制编译器生成错误。
您可以稍微修改一下代码以获得所需的内容。
-
使
A::fn
成为纯虚拟。将实现保留为A
中的原样。请记住,即使它被声明为纯虚拟,实现A::fn
也是完全可以的。 -
这将迫使您覆盖
fn
B
.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.
相关文章:
- 在 C++ 中用派生类型重写成员函数
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 重写派生类中的二元运算符
- 具有派生参数的函数重写
- 我无法重写基类的方法,因为我的派生类是模板化的
- 派生类中的私有重写虚函数
- 哪个基类调用派生重写的方法?
- 不要重写派生类中的纯虚函数
- 基类能否知道派生类是否已重写虚拟方法
- 是否有可能有一个派生类继承最终函数但创建相同的函数(而不是重写)
- Qt/C++ - 从派生类调用重写方法
- 重写派生类中的枚举值
- 使派生类使用重写运算符
- C ++中有没有办法让派生类重写基类静态方法
- 重写派生类中的模板基方法?
- 在派生类中重写哪个基类的虚拟析构函数
- 在多级继承中重写,中间派生类未覆盖函数
- 有没有一种技术可以使虚函数在所有派生类中强制重写?
- 在继承时用指向派生类的指针重写指向基类的指针
- 是否可以在不重写派生类中记录虚拟成员?