如何调用基类的虚函数,该函数是函数的输入参数

How to call a base class's virtual function that is an input argument to a function

本文关键字:函数 输入 参数 何调用 调用 基类      更新时间:2023-10-16

使用C++,我有

struct Base {
    virtual void stuff(/*base stuff*/);
};
struct Derived : public Base {
    void stuff(/*derived stuff*/); 
};
void function1(Derived& obj){
   obj.stuff(); 
}

在这种情况下,function1 将使用 Derived 的 do() 函数。如果在函数 1 中,我想调用基类的 do() 函数怎么办?如果我调用函数 1 作为,它会起作用吗 function1(dynamic_cast<Base*>(derived_obj_ptr))

在纠正代码中的大量错误后,这确实是可以实现的:

#include <iostream>
class Base {
public:
    virtual void foo() { std::cout << "Basen"; }
};
class Derived : public Base {
public:
    void foo() { std::cout << "Derivedn"; }
};
void function1(Derived *p) {
   p->Base::foo();  // <<<<< Here is the magic >>>>>
}
int main() {
    Derived d;
    function1(&d);
}

输出:

Base

(见 http://ideone.com/FKFj8)