Can I get polymorphic behavior without using virtual functions?(我可以在不使用虚函数的情况下获得多态行为吗?)
问题描述
由于我的设备,我无法使用虚拟功能.假设我有:
Because of my device I can't use virtual functions. Suppose I have:
class Base
{
void doSomething() { }
};
class Derived : public Base
{
void doSomething() { }
};
// in any place
{
Base *obj = new Derived;
obj->doSomething();
}
obj->doSomething() 将只调用 Base::doSomething()
Base *obj有没有办法调用Derived的doSomething?
我知道我可以在 Base 的 doSomething() 之前放置一个 virtual 来解决问题,但我受限于我的设备,编译器不支持.
I know I can just put a virtual before doSomething() of Base it solve the problem, but I'm limited by my device, the compiler doesn't support it.
推荐答案
您可以将基类指针向下转换为派生类并调用函数.
You could down cast the base class pointer to the derived class and call the function.
Base* obj = new Derived;
Derived* d = static_cast<Derived*>( obj );
d->doSomething();
由于 doSomething() 没有被声明为 virtual,你应该得到派生的实现.
Since doSomething() is not declared virtual, you should get the derived implementation.
这篇关于我可以在不使用虚函数的情况下获得多态行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以在不使用虚函数的情况下获得多态行为吗?
基础教程推荐
- C语言3个整数的数组 1970-01-01
- C语言数组 1970-01-01
- 总计将在节日礼物上花多少钱 1970-01-01
- C++多态 1970-01-01
- 对 STL 容器的安全并行只读访问 2022-10-25
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- 用指数格式表示浮点数 1970-01-01
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- 明确指定任何或所有枚举数的整数值 1970-01-01
