gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:39:40 24 4
gpt4 key购买 nike

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

class Base {
public:
virtual void foo() {
cout << "base::foo" << endl;
bar();
}
virtual void bar() {
cout << "base::bar" << endl;
}
};

然后我想创建一个包装类,其中每个方法都调用基类方法和一些我用于某些测试的附加内容。
class Derived :public Base {
public:
void foo() override {
cout << "derived::foo" << endl;
Base::foo();
}
void bar() override {
cout << "derived::bar" << endl;
Base::bar();
}
};

我的程序从基类调用函数,我已将其更改为从派生类调用。
int main() {
//Base A;
Derived A;
A.foo();
return 0;
}

在上面的例子中,当我调用 Derived::foo() 时,它调用了 Base::foo(),而后者又调用了 bar();由于多态性,当从 Base::foo() 调用 bar() 时,它被解析为 Derived::bar()。我希望 Base::foo() 调用 Base::bar() 并且只有来自 Derived 的调用才能调用 Base 方法。是否可以在不修改基类的情况下实现这一点?

最佳答案

您可以通过限定函数的名称来使用静态分派(dispatch)到虚函数:

virtual void foo() {
cout << "base::foo" << endl;
Base::bar();
}

Is it possible to achieve this without modifying the base class?



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

关于c++ - 如何避免基类中的多态调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60948665/

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