问题描述
我有一个基类
class ShapeF
{
public:
ShapeF();
virtual ~ShapeF();
inline void SetPosition(const Vector2& inPosition) { mPosition.Set(inPosition); }
protected:
Vector2 mPosition;
}
显然有一些省略的代码,但你明白了.我使用它作为模板,并通过一些有趣的(省略)枚举来确定我正在使用的形状类型
Obviously with some ommitied code, but you get the point.I use this as a template, and with some fun (ommited) enums, a way to determine what kind of shape i'm using
class RotatedRectangleF : public ShapeF
{
public:
RotatedRectangleF();
virtual ~RotatedRectangleF();
protected:
float mWidth;
float mHeight;
float mRotation;
}
ShapeF 通过定位和一个定义类型的枚举来完成它的工作.它有访问器和修改器,但没有方法.
ShapeF does its job with the positioning, and an enum that defines what the type is.It has accessors and mutators, but no methods.
我可以将 ShapeF 设为抽象类,以确保没有人尝试实例化 ShapeF 类型的对象吗?
Can I make ShapeF an abstract class, to ensure nobody tries and instantiate an object of type ShapeF?
通常,这可以通过在 ShapeF 中使用纯虚函数来实现
Normally, this is doable by having a pure virtual function within ShapeF
//ShapeF.h
virtual void Collides(const ShapeF& inShape) = 0;
但是,我目前正在处理一个单独的类中的冲突.我可以移动一切,但我想知道是否有一种方法可以使类抽象..没有纯虚函数.
However, I am currently dealing with collisions in a seperate class.I can move everything over, but i'm wondering if there is a way to make a class abstract.. without the pure virtual functions.
推荐答案
你可以声明、并实现一个纯虚拟析构函数:
You could declare, and implement, a pure virtual destructor:
class ShapeF
{
public:
virtual ~ShapeF() = 0;
...
};
ShapeF::~ShapeF() {}
这是您已有的一小步,并且会阻止 ShapeF
被直接实例化.派生类不需要更改.
It's a tiny step from what you already have, and will prevent ShapeF
from being instantiated directly. The derived classes won't need to change.
这篇关于没有纯虚函数的C++抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!