使用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()函数。如果在function1中,我想调用Base类的do()函数呢?如果我将function1称为as,它会工作吗?
function1(dynamic_cast<Base*>(derived_obj_ptr))
?
答案 0 :(得分:7)
在纠正代码中的大量错误之后,这确实是可以实现的:
#include <iostream>
class Base {
public:
virtual void foo() { std::cout << "Base\n"; }
};
class Derived : public Base {
public:
void foo() { std::cout << "Derived\n"; }
};
void function1(Derived *p) {
p->Base::foo(); // <<<<< Here is the magic >>>>>
}
int main() {
Derived d;
function1(&d);
}
输出:
Base