c++ - 无法在 C++ 的派生类中重载基类方法

标签 c++ methods overloading base-class

我想做什么

我正在将现有代码库转换为基于访问者模式的方案,该代码库使用 dynamic_casting 来识别派生类(形状)以应用派生类特定处理。为此,我在基类(虚拟)和每个派生类中添加了一个 processMe 方法,并在 ShapeProcessor 类中添加了一个 handleShape 方法,一个用于要处理的每种类型的形状,典型的访问者模式。我有一个 ShapeProcessor 抽象基类,它有一个纯虚拟方法,强制用户提供一个捕获所有形状处理器,并允许用户从 ShapeProcessor 派生并根据需要添加其他形状处理方法(例如 MyShapeProcessor : public ShapeProcessor)

观察

然而,我发现只有 catch all 方法在 MyShapeProcessor 中为所有形状调用,我的形状特定方法没有被调用。我需要做什么才能根据需要调用特定于形状的方法?警告:如果我将所有处理程序方法放在一个类中,它就可以正常工作。这是否意味着不能重载基类中的方法?我已经阅读了关于隐藏姓名的帖子,但这似乎不适用于此处。或者是吗?我尝试使用“using”取消隐藏基类方法,但似乎没有帮助。

这是伪代码示例:

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 作为虚拟 成员函数。否则,此函数在任何 processMe 函数中都不可见。

class ShapeProcessor {
    virtual void processShape (Shape& shape) = 0;

    virtual void processShape (Circle& circle) = 0;

};

当您在项目中添加新的 Shape 子类型时,您必须返回到 ShapeProcessor 并添加一个新的 processShape子类型的函数。

您可以使用模板来避免这种紧耦合。看看https://stackoverflow.com/a/7877397/434551 .

关于c++ - 无法在 C++ 的派生类中重载基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25468255/

相关文章:

c++ - 转换构造函数不会将 "2"转换为运算符 + 中的用户定义类型

c++ - 全局类型转换运算符重载?

c++ - 在opencv c++(移动相机)上检测运动

c++ - 避免缩小 c 样式数组创建时的警告

class - 为什么我不能定义 `delete` 方法?

c# - 在 asp.net 中验证 .cs 文件中的方法

java - 调用链的潜在问题

c# - 动态转换问题

c++ - 我的矩阵类在初始化时崩溃

c++ - 使用 CryptoPP::HexDecoder( )