gpt4 book ai didi

c++ - 比 C++ 中的 dynamic_cast 更好的解决方案

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:45:01 26 4
gpt4 key购买 nike

我有一个为我的项目设计的类层次结构,但我不确定如何实现它的一部分。

这是类层次结构:

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
}

最佳答案

你可以使用装饰器模式:

class ColorDecorator public Colored
{
ColorDecorator(Shape* shape): m_shape(shape) {}
... //forward/implement whatever you want
};

如果您想将 Square 存储在 Colored vector 中,请将其包装在这样的装饰器中。

但这是否有意义值得怀疑,这取决于您的设计和备选方案。为了以防万一,还要检查访问者模式(也称为双重分派(dispatch)),您可以使用它来访问容器中的对象子集或根据对象的类型以不同方式对待它们。

关于c++ - 比 C++ 中的 dynamic_cast 更好的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23569140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com