我有一个类层次结构,是为我的项目设计的,但我不确定如何实现其中的一部分。
这是类层次结构:
class Shape { };
class Colored { // Only pure virtual functions
};
class Square : public Shape { };
class Circle : public Shape { };
class ColoredSquare : public Square, public Colored { };
class ColoredCircle : public Circle, public Colored { };
在我的项目中,我有一个包含不同类型形状的std::vector。然而,为了运行某个算法,我需要将它们放入一个std::vector的彩色对象中(所有这些对象都是不同具体形状的派生类型),因此我需要一种方法在运行时将Square转换为ColoredSquare,将Circle转换为ColoredCircle。
棘手的问题在于,“形状”类与“彩色”类位于不同的库中。
如何最好地完成这个任务?我考虑过进行dynamic_cast检查,但如果有更好的方法,我宁愿采用那种方法。
编辑1:
以下是一个更好的示例:
class Traceable {
public:
// All virtual functions
virtual bool intersect(const Ray& r) = 0;
// ...
};
class TraceableSphere : public Sphere, public Traceable {
};
class IO {
public:
// Reads shapes from a file, constructs new concrete shapes, and returns them to
// whatever class needs them.
std::vector<Shape*> shape_reader(std::string file_name);
};
class RayTracer {
public:
void init(const std::vector<Shape*>& shapes);
void run();
private:
std::vector<Traceable*> traceable_shapes;
};
void RayTracer::init(const std::vector<Shape*>& shapes) {
// ??? traceable_shapes <- shapes
}
void RayTracer::run() {
// Do algorithm
}