dynamic_cast(pb) return null

后端 未结 2 760
青春惊慌失措
青春惊慌失措 2021-01-21 19:55

In C++ primer(5th) 19.2.1 about dynamic_cast. It says, for dynamic_cast(e) to be successful,

the type of e must be either a cla

2条回答
  •  故里飘歌
    2021-01-21 20:46

    dynamic_cast can be used as a tool to detect if an object is derived from another one or not, in the code you've written, the answer is NO, so you got a null. By

    B *pb = new B;
    D *pd = dynamic_cast(pb);
    

    You're down-casting a base to a derived, and it is reverse of what the documet is saying. Of course you can have below if pb points to an extact D*:

    B *pb = new D; // <--- It is a `D`
    D *pd = dynamic_cast(pb);
    

提交回复
热议问题