类型转换二:Type casting

来源:互联网 发布:const javascript 编辑:程序博客网 时间:2024/05/01 03:24

C++ is a strong-typed language. There exist two main syntaxes for generic type-casting: functional and c-like:
C++是强类型语言。有两种主要的通用类型转换语法:函数上的 & 类C的。

double x = 10.3;int y;y = int (x);    // functional notation函数上y = (int) x;    // c-like cast notation类C可恶意

这两种类型转换格式,在功能上足以满足基础数据类型的大多数需要。然而,这些操作可以被不加区分的使用在类以及指向类的指针上,这可能会导致运行时错误(虽然语法上市正确的)。
下面的代码在编译时没有错误:

// class type-casting#include <iostream>using namespace std;class Dummy {    double i,j;};class Addition {    int x,y;  public:    Addition (int a, int b) { x=a; y=b; }    int result() { return x+y;}};int main () {  Dummy d;  Addition * padd;  padd = (Addition*) &d;  cout << padd->result();  return 0;}

Addition类型的指针padd被指向了,与之毫无关联的Dummy类型d上。在后续的result成员调用中,将会导致运行时错误/其他未料的结果。
原因是:未加限制的显式类型转换允许将任意类型的指针指向其他类型的指针。

为了控制类之间的这种类型转换,我们有四种特定的类型转换操作:
dynamic_cast , reinterpret_cast, static_cast, const_cast;
再加上上面的转换共有五种(c-like的那种不提倡):

dynamic_cast <new_type> (expression)reinterpret_cast <new_type> (expression)static_cast <new_type> (expression)const_cast <new_type> (expression)new_type(expression); // 实际上这是面向对象的思想。看看像不像是一个构造函数???

dynamic_cast

dynamic_cast可以被用在指向类的指针或者引用(或者用在void *上)。它的目的是为了确保指针在转换之后可以指向一个有效的完整目标类型。
指针向上(upcast)转换:converting from pointer-to-derived to pointer-to-base指向派生类指针转换为指向基类指针—-隐式转换。
指针向下(downcast)转换:convert from pointer-to-base to pointer-to-derived指向基类指针转换为指向派生类指针(多态类,需要virtual成员支持),这也仅仅是在指针式一个有效的完整的目标类型才行。

#include <iostream>#include <exception>using namespace std;class Base { virtual void dummy() {} };class Derived: public Base { int a; };int main () {  try {    Base * pba = new Derived;    Base * pbb = new Base;    Derived * pd;    pd = dynamic_cast<Derived*>(pba);    if (pd==0) cout << "Null pointer on first type-cast.\n";    pd = dynamic_cast<Derived*>(pbb);    if (pd==0) cout << "Null pointer on second type-cast.\n";  } catch (exception& e) {cout << "Exception: " << e.what();}  return 0;}

输出:

Null pointer on second type-cast.

pba & pbb 都是Base*类型的指针。实际上pba指向派生类,pbb指向基类。因此,当他们分别使用dynamic_cast时(向下转换),pba指向一个完整的派生类对象,但是pbb指向基类的对象。因此,pbb指向的并不是一个完整的派生类对象。
向下转换时,如果转换失败返回NULL指针。如果使用dynamic_cast转换一个引用类型,并且转换不可行时,会抛出bad_cast异常。

dynamic_cast can also perform the other implicit casts allowed on pointers: casting null pointers between pointers types (even between unrelated classes), and casting any pointer of any type to a void* pointer.
dynamic_cast允许其他的隐式转换:null指针和指针(null指针和非null指针)类型之间的转换。把任何类型的指针转换为void* 指针。

static_cast
reinterpret_cast
const_cast
typeid

0 0
原创粉丝点击