dynamic_cast和 static_cast的区别

(dynamic_cast)必须要有虚函数才能进行转换,static_cast静态转换,不安全。)

运行时类型信息通过运算符dynamic_cast来提供。dynamic_cast用来向下转型,将基类指针转换为派生类指针.(把基类指针转换为派生类指针)向下转型,向上转型的话就用强制转换。

运算符dynamic_cast<T*>ptr)用来将一个指针类型转换为另外一个指针类型。它经常用来检查一个基类指针是否实际指向的是派生类对象。

static_cast<type-id > ( expression )  

1. static_cast(expression) The static_cast<>() is used to cast between the integer types. 'e.g.' char->long, int->short etc.

用来数值之间的转化。

2.  可以在相关指针之间转换,指针在void *之间转换,还可以在基类和派生类之间转换。 这些转换是在编译的时候就确定下来转换(无非就是根据继承关系,偏移指针而已),但是这需要自己保证安全。

#include <iostream>

using namespace std;

class Base

{

public:

    virtual void f() {cout<<"Base::f()"<<endl;}

};

class Derive: public Base

{

public:

    virtual  void f() {cout<<"Derive::f()"<<endl;}

    virtual  void f2() {cout<<"Derive::f1()"<<endl;}

}

int main()

{

    Base *pbase1  = new Derive();

    Derive* pderive1 = static_cast<Derive *>(pbase1);

    pderive1->f(); // Derive::f()

    

    Base* pbase2 = new Base();

    Derive * pderive2 = static_cast<Derive *>(pbase2);

    pderive2->f();  // Base::f()

    pderive2->f2(); // throw exception "Access violation reading"

 

    delete pbase1;

    delete pbase2;

}

虽然 pbase2转化到 pderive2,编译器编译正确。 但是当调用 pderive2->f();应该不是希望的; 调用pderive2->f2()因为基类本身就没有这个函数,说以运行时出错,抛出异常。

所以说static_cast 是编译时确定下来,需要自己确保转换类型安全,否则运行时会抛出异常.

注意static_cast 不能直接在没有继承关系的对象指针之间进行转换。在Com 里面实现不同接口的同个对象,其也不能再接口之间转换(更何况是动态的),所以COM提供一个query借口。

 

用法:dynamic_cast < type-id > ( expression)

是专门用于具有继承关系的类之间转换的,尤其是向下类型转换,是安全的。

#include <iostream>

using namespace std;

class Base

{

public:

virtual void f() {cout<<"Base::f()"<<endl;}

};

class Derive: public Base

{

public:

virtual void f() {cout<<"Derive::f()"<<endl;}

virtual void f2() {cout<<"Derive::f1()"<<endl;}

};

int main()

{

Base *pbase1 = new Derive();

Derive* pderive1 = dynamic_cast<Derive *>(pbase1); //down-cast

pderive1->f(); // Derive::f()

 

Base* pbase2 = new Base();

Derive * pderive2 = dynamic_cast<Derive *>(pbase2); //up-cast

if ( pderive2) // NULL

{

pderive2->f();

pderive2->f2();

}

delete pbase1;

delete pbase2;

 

}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值