如何在C++中找到变量派生最多的子类?
How to find the most derived subclass of a variable in C++?
IDK 如果问题有帮助,但在C++可以执行以下操作:
PinAbstract* pin1 = new ValuedPin<int>();
ValuedPin<int>* pin2 = new ValuedPin<int>();
std::cout << (get_most_derived_subclass(pin1) == get_most_derived_subclass(pin2)) << std::endl;
//OUTPUT should be:
1 <- Since both are at most ValuedPin<int>*'s, even if pin1 is declared as PinAbstract.
其中 PinAbstract 是 ValuedPin 的超类。typeid
不适用于指针和值,因为对于 pin1,它返回 PinAbstract。
简短的回答是否定的,你问的是不可能的,因为C++没有比get_most_derived_subclass()
更好的了。
但是,对于多态类型(具有virtual
方法的类型(,可以使用dynamic_cast
来确定给定对象是否实现了给定类型,例如:
PinAbstract* pin1 = ...;
std::cout << (dynamic_cast<ValuedPin<int>*>(pin1) != NULL) << std::endl;
相关文章:
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 避免在C++中重复子类定义
- 将QOpenGLWidget子类转换为使用Metal而不是OpenGL的子类是否可行?
- 如何初始化矢量的模板化子类
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 使用子类覆盖基类中定义的函数
- 如何在C++中找到变量派生最多的子类?
- 将方法参数类型更改为子类中的派生类
- C++ 函数无法使用模板为基类的子类派生模板
- 类和子类 - 从派生类发送到主要类的数据
- 采用指向基类的指针的函数是否也接受从基类私下派生的子类?
- 获取基派生(子)类对象中的基类指针(父级)
- C++,使用基类指针存储子类和使用派生类方法的策略
- 我怎样才能从模板派生两次,并让子类交互
- 隐藏从子类隐式派生自(c++)的方法