【发布时间】:2014-10-17 13:28:28
【问题描述】:
我要做什么
我正在将使用 dynamic_casting 识别派生类(形状)以应用派生类特定处理的现有代码库转换为基于访问者模式的方案。为此,我在基类(虚拟)和每个派生类中添加了一个 processMe 方法,并在 ShapeProcessor 类中添加了一个 handleShape 方法,用于处理每种类型的形状,这是访问者模式的典型。我有一个 ShapeProcessor 抽象基类,它有一个纯虚拟方法,该方法强制用户提供一个捕获所有形状处理器并允许用户从 ShapeProcessor 派生并根据需要添加其他形状处理方法(例如 MyShapeProcessor : public ShapeProcessor)
观察
但是发现只有在 MyShapeProcessor 中为所有形状调用了 catch all 方法,而我的形状特定方法没有被调用。我需要做什么才能根据需要调用特定于形状的方法?警告:如果我将所有处理程序方法放在一个类中,它就可以正常工作。这是否意味着不能重载基类中的方法?我已阅读有关名称隐藏的帖子,但这似乎不适用于此处。或者是吗?我尝试使用“使用”取消隐藏基类方法,但似乎没有帮助。
下面是伪代码示例:
class Shape {
virtual void processMe (ShapeProcessor * sp) {
sp->processShape (*this);
}
// User derived shape
class Circle : public Shape {
void processMe (ShapeProcessor * sp) {
sp->processShape (*this);
}
// Base ShapeProcessor
class ShapeProcessor {
virtual void processShape (Shape& shape) = 0; // User must provide a catch all method
}
// User provided shape processor
class MyShapeProcessor : public ShapeProcessor {
void processShape (Circle& circle) {
// Never gets called, even for Circle objects!
}
void processShape (Shape& shape) {
// Always gets called for all shapes!
cout << "Unsupported shape!" << endl;
}
}
// User code
Circle * circle = new Circle();
MyShapeProcessor * sp = new MyShapeProcessor();
circle->processMe (sp);
// Expecting processMe to eventually call MyShapeProcessor processShape (Circle) but calls processShape (Shape)
// Caveat: If I get rid of the ShapeProcessor base class and if I put all shape handles in a single class
// it works fine. Does this mean that it is not possible to overload methods in the base class? I have read
// the posts on name hiding, but that does not seem to apply here. Or does it?
【问题讨论】:
-
我建议,在你继续之前,你选择一种编程语言来使用。
-
谢谢,我在标签和标题中添加了 C++。我希望这就是我需要做的一切? (我是一个不常发帖的人)
标签: c++ methods overloading base-class