如何调用基类的虚函数,该函数是函数的输入参数
How to call a base class's virtual function that is an input argument to a function
使用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)
相关文章:
- 如果我更改函数输入,我的递归不起作用?
- 初始化与函数输入相关的全局数组
- 如何生成比用户使用 rand() 函数输入的数字大 5-10% 的数字?
- 将函数更改为具有设置函数输入变量的方法的类
- 如何避免将 const 和非 const 成员函数输入到模板中的代码重复
- 是否有一种方法可以避免标头文件中使用的constexpr函数输入全局范围,而无需额外的名称空间
- 迭代器作为C 中的函数输入
- 如何为作为雇员类的指针传入的构造函数输入数据
- 最小的函数输入和输出错误
- C++ 函数输入错误
- QComboBox 作为 QT 中的函数输入参数
- 函数输入之前的分割故障
- 如何在视觉工作室 2012年设置函数输入参数的颜色
- 函数输入变化
- 使用函数输入 1 个 int 和 1 个字符串数组并循环
- 将数组用于函数输入参数
- 如何在c++中将函数输入强制转换为智能指针
- 自定义检查器的覆盖率引用函数输入
- 为什么我不能使用两个scanf函数输入字母
- 犰狳cov函数输入