问题
I have a base class
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 does its job with the positioning, and an enum that defines what the type is. It has accessors and mutators, but no methods.
Can I make ShapeF an abstract class, to ensure nobody tries and instantiate an object of type 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.
回答1:
You could declare, and implement, a pure virtual destructor:
class ShapeF
{
public:
virtual ~ShapeF() = 0;
...
};
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.
回答2:
Try using a protected constructor
回答3:
If your compiler is Visual C++ then there is also an "abstract" keyword:
class MyClass abstract
{
// whatever...
};
Though AFAIK it will not compile on other compilers, it's one of Microsoft custom keywords.
来源:https://stackoverflow.com/questions/14631685/c-abstract-class-without-pure-virtual-functions