Dynamic down cast to abstract class (C++)

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

I am trying to learn some object orientated programming aspect I know from java in C++. However I am having some difficulties in using dynamic_cast where I would use instanceof in Java.

I have a base class Cell and a derived (abstract) class Obstacle. I have defined it like this: Obstacle : public Cell and Obstacle contains a pure virtual destructor. Now in the Cell class I want to implement a method bool Cell::isAccesible(). I've implemented this as follows:

bool Cell::isAccessible() {      Obstacle *obs = dynamic_cast<Obstacle*>(this);      if (obs != NULL) return false;     return true; } 

However I get the following error back:

"the operand of a runtime dynamic_cast must have a polymorphic class type".

What's wrong with the way I want to implement this? Any guidance is appreciated.

回答1:

Cell class must have at least one virtual function to use dynamic_cast. Also, if Cell is your base class, it should have a virtual destructor.

You should make isAccessible a virtual function and override it in Obstacle to return false.



回答2:

What you're doing is wrong. Generally you shouldn't need to cast to a sub type of a class in its base class. If you need it, it is likely a design error. In your case the code should look like this.

virtual bool Cell:: isAccessible() {   return true; }  bool Obstacle::isAccessible() {   return false; } 

P.S. The cause of your error is that Cell class does not have a virtual method and thus it does not show polymorphic behaviour.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!