动态向下转换为抽象类(C ++) [英] Dynamic down cast to abstract class (C++)

查看:134
本文介绍了动态向下转换为抽象类(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从C ++中的Java学习一些面向对象的编程方面的知识.但是,在Java中使用instanceof的地方,在使用dynamic_cast时遇到了一些困难.

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.

我有一个基类Cell和一个派生的(抽象)类Obstacle.我已经这样定义:Obstacle : public CellObstacle包含一个纯虚拟析构函数.现在,在Cell类中,我要实现方法bool Cell::isAccesible().我已经实现了如下:

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:

"运行时dynamic_cast的操作数必须具有多态类 类型".

"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.

推荐答案

Cell类必须至少具有一个虚拟函数才能使用dynamic_cast.另外,如果Cell是您的基类,则它应该具有虚拟析构函数.

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.

您应该将isAccessible设为虚拟函数,并在Obstacle中覆盖它以返回false.

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

这篇关于动态向下转换为抽象类(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆