C++:从抽象指针向量中获取继承的类型
C++ : get inherited type from abstract pointer vector
所以我有一个向量,它包含Component抽象类的指针
,假设我有两个从Component、foo和bar继承的类,有什么方法可以从这个向量中获得类型为"foo"的指针吗
vector<Component*> components;
class foo : Component;
class bar : Component;
components.push_back(new foo());
components.push_back(new bar());
谢谢。
是的:
Component* c = components[0];
if (foo* f = dynamic_cast<foo*>(c)) {
// use f
}
else {
// c is not a foo. Maybe it's a bar, or something else
}
因此,如果你想写一个函数来查找foo*
,你可以这样做(假设C++11):
foo* find_foo(const std::vector<Component*>& components)
{
for (auto c : components) {
if (foo* f = dynamic_cast<foo*>(c)) {
return f;
}
}
return nullptr;
}
强制转换dynamic_cast<foo*>
将返回有效的foo*
或nullptr
,它不会抛出。根据标准§5.2.7.9:
失败的强制转换为指针类型的值是所需结果类型的空指针值。
是的,您可以通过使用RTTI的概念来实现:-
#include <typeinfo>
//Using for loop iterate through all elements
if ( typeid(*iter) == typeid(Foo) )
//You got the Foo object
但这在C++中几乎从来都不可取。
相关文章:
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- C++获取所有继承类信息的方法
- 从继承的C 类获取模板类型
- 获取 CRTP 继承链中最深的类
- 获取继承的实例化模板的类型
- 获取继承基类类型的元组
- 获取多重继承中基类的编译时常量偏移量
- C++继承:如何获取被调用对象的大小
- 如何为类的继承层次结构的获取者创建统一的接口
- 如何获取继承类C++的信息
- C++:从抽象指针向量中获取继承的类型
- std::tuple,按继承类型获取项
- 在(私有)继承向量<string>上获取迭代器
- 获取一个类的所有继承类
- 从虚基类获取继承路径
- 如何从多重继承的基础中获取类地址?
- 在c++中获取一个类的指针,该类是另一个具有多重继承的类的一部分
- 如何获取c++代理/服务类中继承的soap结构的引用
- 获取继承了enable_shared_from_this的类的unique_ptr
- c++继承.获取基类的数据成员值