如何避免基类中的多态调用

Pop*_*tin 3 c++ polymorphism

我有一个类,其中某些方法调用其他方法,如下例所示:

class Base {
public:
    virtual void foo() {
        cout << "base::foo" << endl;
        bar();
    }
    virtual void bar() {
        cout << "base::bar" << endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后我想创建一个包装类,其中每个方法都调用基类方法以及我用于某些测试的一些附加内容。

class Derived :public Base {
public:
    void foo() override {
        cout << "derived::foo" << endl;
        Base::foo();
    } 
    void bar() override {
        cout << "derived::bar" << endl;
        Base::bar();
    }
};
Run Code Online (Sandbox Code Playgroud)

我的程序从基类调用函数,我已将其更改为从派生类调用。

int main() {
    //Base A;
    Derived A;
    A.foo();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,当我调用 Derived::foo() 时,它会调用 Base::foo(),后者又调用 bar(); 由于多态性,当从 Base::foo() 调用 bar() 时,它会解析为 Derived::bar()。我希望 Base::foo() 调用 Base::bar() 并且仅从 Derived 调用 Base 方法。是否可以在不修改基类的情况下实现这一目标?

eer*_*ika 5

您可以通过限定函数名称来对虚拟函数使用静态分派:

virtual void foo() {
    cout << "base::foo" << endl;
    Base::bar();
}
Run Code Online (Sandbox Code Playgroud)

是否可以在不修改基类的情况下实现这一目标?

我不这么认为;至少如果您考虑修改基类的成员函数的定义,则不会。