【发布时间】:2009-07-03 18:44:47
【问题描述】:
存储基类指针列表的常见做法是什么?每个基类指针都可以描述多态派生类?
为了详细说明并为了一个简单的示例,假设我有一组具有以下目标的类:
- 一个抽象基类,其目的是在其派生类上实施公共功能。
- 一组派生类:可以执行通用功能,本质上是可复制的(这很重要),并且是可序列化的。
现在,除了这个必需的功能之外,我还想解决以下关键点:
- 我希望这个系统的使用是安全的;当用户错误地将基类指针强制转换为错误的派生类型时,我不希望用户出现未定义的错误。
- 此外,我希望尽可能多地自动处理复制/序列化此列表的工作。这样做的原因是,由于添加了新的派生类型,我不想搜索许多源文件并确保所有内容都兼容。
下面的代码演示了一个简单的案例,以及我提出的(我再次寻找一种经过深思熟虑的通用方法,我的可能不是那么好)解决方案。
class Shape {
public:
virtual void draw() const = 0;
virtual void serialize();
protected:
int shapeType;
};
class Square : public Shape
{
public:
void draw const; // draw code here.
void serialize(); // serialization here.
private:
// square member variables.
};
class Circle : public Shape
{
public:
void draw const; // draw code here.
void serialize(); // serialization here.
private:
// circle member variables.
};
// The proposed solution: rather than store list<shape*>, store a generic shape type which
// takes care of copying, saving, loading and throws errors when erroneous casting is done.
class GenericShape
{
public:
GenericShape( const Square& shape );
GenericShape( const Circle& shape );
~GenericShape();
operator const Square& (); // Throw error here if a circle tries to get a square!
operator const Circle& (); // Throw error here if a square tries to get a circle!
private:
Shape* copyShape( const Shape* otherShape );
Shape* m_pShape; // The internally stored pointer to a base type.
};
上面的代码肯定缺少一些项目,首先,基类将有一个需要类型的构造函数,派生类将在构造过程中内部调用它。此外,在 GenericShape 类中,将存在复制/赋值构造函数/操作符。
抱歉,这篇文章很长,试图充分解释我的意图。关于这一点,并重申:以上是我的解决方案,但这可能有一些严重的缺陷,我很高兴听到它们以及其他解决方案!
谢谢
【问题讨论】:
标签: c++ polymorphism