问题描述
我有一个基类
class ShapeF
{
public:
ShapeF ();
virtual〜ShapeF();
inline void SetPosition(const Vector2& inPosition){mPosition.Set(inPosition); }
protected:
Vector2 mPosition;
}
显然有一些ommitied代码,但你得到的点。
我使用它作为一个模板,并使用一些有趣的(枚举)枚举,一种确定我使用什么样的形状的方法
class RotatedRectangleF:public ShapeF
{
public:
RotatedRectangleF();
virtual〜RotatedRectangleF();
protected:
float mWidth;
float mHeight;
float mRotation;
}
ShapeF通过定位来完成它的工作,是。
它有访问器和变异符,但没有方法。
我可以让ShapeF一个抽象类,以确保没有人尝试和实例化一个ShapeF类型的对象? / p>
通常情况下,这可以通过在ShapeF中拥有一个纯虚函数来实现。
// ShapeF.h
virtual void Collides(const ShapeF& inShape)= 0;
但是,我目前正在处理一个单独的类中的碰撞。
我可以移动一切,但我想知道是否有一个方法来创建一个类抽象..没有纯虚函数。
您可以声明,并实现一个纯虚拟析构函数:
class ShapeF
{
public:
virtual〜ShapeF()= 0;
...
};
ShapeF ::〜ShapeF(){}
从你已经有,并将阻止 ShapeF
直接实例化。派生类不需要更改。
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.
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.
这篇关于C ++抽象类没有纯虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!