我想做什么
我正在将使用dynamic_casting来标识派生类(形状)以应用派生类特定处理的现有代码库转换为基于访问者模式的方案。为此,我在基类(虚拟)中添加了processMe方法,并在每个派生类中添加了ShapeShape类的handleShape方法,每种要处理的形状类型(典型的访客模式)都添加了一个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?
您需要添加:
void processShape (Circle& circle);
到ShapeProcessor
作为virtual
成员函数。否则,该功能将无法从任何功能中看到processMe
。
class ShapeProcessor {
virtual void processShape (Shape& shape) = 0;
virtual void processShape (Circle& circle) = 0;
};
在项目中添加的新子类型时Shape
,您必须返回ShapeProcessor
并processShape
为该子类型添加新功能。
您可以使用模板来避免这种紧密耦合。看看https://stackoverflow.com/a/7877397/434551。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句