c++ cast

dynamic_cast

dynamic_cast运算符的主要用途:将基类的指针或引用安全地转换成派生类的指针或引用,并用派生类的指针或引用调用非虚函数。如果是基类指针或引用调用的是虚函数无需转换就能在运行时调用派生类的虚函数。

如果一条dynamic_cast语句的转换目标是指针类型且转换失败,则返回一个空指针,则判断条件为0,即为false;如果转换成功,指针为非空,则判断条件为非零,即true。

前提条件:将dynamic_cast用于某种类型的指针或引用时,该类型必须含有至少一个虚函数时,才能进行这种转换。否则,编译报错禁止(原因:Dynamic_cast转换是在运行时进行转换,运行时转换就需要知道类对象的信息(继承关系等)。如何在运行时获取到这个信息——虚函数表。因此是不得而为之)。

示例:

#include <stdio.h>

#include <array>

#include <iostream>

using namespace std;

class Widget {

public:

  virtual ~Widget(){}  //the base class must have at least one virtual function

  //virtual void init(){}

  void test(){}

};

class HisWidget:public Widget {};

class MyWidget:public Widget {};

void verify_cast_result(const char *desp, HisWidget *result){

  printf("%s - result: %x\n\n", desp, result);

}

void test_dynamic_cast()

{

  Widget *pw1 = new HisWidget();

  Widget *pw2 = new Widget();

  Widget *pw3 = new MyWidget();

  Widget *pw4 = nullptr;

  Widget *pw5;//unitial and random value

 

  //build ok, run ok, cast ok

  verify_cast_result("HisWidget's base form cast-> HisWiget", dynamic_cast<HisWidget *>(pw1));

 

  //build ok, run ok, cast failed

  verify_cast_result("Base cast->HisWidget", dynamic_cast < HisWidget * >(pw2));

 

  //build ok, run ok, cast failed

  verify_cast_result("MyWidget cast->HisWidget", dynamic_cast<HisWidget *>(pw3));

 

  //build ok, run ok, cast failed

  verify_cast_result("nullptr cast->HisWidget", dynamic_cast < HisWidget * >(pw4));

 

  //build ok, run ok, cast ok but dangours.

  verify_cast_result("Base force-> HisWidget ", (HisWidget *) (pw3));

  verify_cast_result("MyWidget force-> HisWidget ", (HisWidget *) (pw3));

  verify_cast_result("unitial pointer force-> HisWidget ", (HisWidget *) (pw5));

 

  cout << "try do dynamic_cast from uninitial pointer to drived class\n";

  try {

    //build ok, run crash, so DON'T do cast uninitial pointer.

    verify_cast_result("unitial pointer cast-> HisWidget", dynamic_cast < HisWidget * >(pw5));

  }

  catch( ...) {

    cout << "dyanmaic_cast error\n";

  }

}

 

int main(int argc, char **argv)

{

  test_dynamic_cast();

  return 0;

}

运行结果

HisWidget's base form cast-> HisWiget - result: 236cc20

 

Base cast->HisWidget - result: 0

MyWidget cast->HisWidget - result: 0

nullptr cast->HisWidget - result: 0

Base force-> HisWidget  - result: 236cc40

MyWidget force-> HisWidget  - result: 236cc60

unitial pointer force-> HisWidget  - result: 400f5d

try do dynamic_cast from uninitial pointer to drived class

Segmentation fault (core dumped)

 

 

posted @ 2019-06-28 17:27  Reboost  阅读(500)  评论(0编辑  收藏  举报