(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;
}
本文详细介绍了 C++ 中 static_cast 和 dynamic_cast 的使用方法及其区别。重点讲述了如何安全地在基类和派生类之间进行类型转换,并通过示例代码展示了这两种类型转换操作符的应用场景。
1103

被折叠的 条评论
为什么被折叠?



