C++ - typeid(), used on derived class doesn't return correct type

前端 未结 3 760
情话喂你
情话喂你 2021-01-05 02:22

Maybe I\'m misunderstanding how inheritance works here, but here\'s my problem:

I have a class Option, and a class RoomOption that derives from it. I have another cl

3条回答
  •  耶瑟儿~
    2021-01-05 03:02

    The type of object a shared_ptr points to is part of its value, not its type. So this line of code is broken:

    cout<getRoom()->getOption(0)).name()<

    You want this:

    cout<getRoom()->getOption(0).get()).name()<

    Or perhaps:

    cout<getRoom()->getOption(0))).name()<

    What typeid does is tell you the actual type of the thing you passed to it. You passed it a shared_ptr. It doesn't look inside the object to see what it contains.

提交回复
热议问题