C ++ - typeid(),用于派生类不返回正确的类型 [英] C++ - typeid(), used on derived class doesn't return correct type
问题描述
也许我误解了继承如何在这里,但这里是我的问题:
Maybe I'm misunderstanding how inheritance works here, but here's my problem:
我有一个类Option和一个类RoomOption从它派生。我有另一个类房间拥有一个矢量的shared_ptrs。在主要我添加一个RoomOption到该向量。然后,使用typeid()我检查类型,它告诉我一个选项。从我已经阅读,typeid应该返回派生类型,和shared_ptrs不会导致切片,所以我不知道我做错了什么。
I have a class Option, and a class RoomOption that derives from it. I have another class Room which holds a vector of shared_ptrs. In main I add a RoomOption to that vector. Then, using typeid() I check the type, and it tells me its an Option. From what I've read, typeid is supposed to return derived types, and shared_ptrs dont cause slicing, so I'm not sure what I'm doing wrong.
以下是代码:
Room.h:
vector<shared_ptr<Option> > options;
void addOption(shared_ptr<Option>);
shared_ptr<Option> getOption(int);
Room.cpp:
void Room::addOption(shared_ptr<Option> option){
options.push_back(option);
}
shared_ptr<Option> Room::getOption(int i){
return options[i];
}
main:
shared_ptr<Room> outside(new Room(0, "", ""));
outside->addOption(shared_ptr<RoomOption>(new RoomOption(0, "Go inside", hallway)));
cout<<typeid(player->getRoom()->getOption(0)).name().get()<<endl;
//This line prints "class std::tr1::shared_ptr<class Option>
发生在我看来,当添加或获得一个选项,RoomOption被强制转换为一个选项,由于返回/参数类型。如果是这样的情况下,我应该存储一个多个类型的向量?我得到这个错误?= \
It occurs to me that maybe when adding or getting an Option, the RoomOption is casted as an Option due to the return/argument type. If that's the case then how am I supposed to store a vector of more than one type? Or am I getting this all wrong? =\
推荐答案
首先获取shared_ptr的typeid。
First of all yor getting the typeid of the shared_ptr.
然后,您应该使用 dynamic_cast 而不是typeid。例如:
Then you should use dynamic_cast instead of typeid. E.g:
if (dynamic_cast<RoomOption*>(player->getRoom()->getOption(0).get()) != 0){
cout << "Its a RoomOption!" << endl;
}
这篇关于C ++ - typeid(),用于派生类不返回正确的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!