C++类型转化分析:静态转换->static_cast

来源:互联网 发布:淘宝哪家茶叶店好 编辑:程序博客网 时间:2024/06/06 05:43

static_cast转换
    static_cast<type-id>(expression)
    该运算符把expression转换成type-id类型的,但是该转换是不安全的,因为没有进行类型安全检查
    staic_cast不仅可以作用于指针和引用,还可以作用于基本数据对象
用法如下:
    1 基类和子类之间指针或者引用的转换
    上行转换(子类的指针或者引用转换成基类的)是安全的
    下行转换(基类的指针或者引用转换成子类的)是不安全的
例子:
class Parents{
public:
    virtual ~Parents(){}
    /*codes here*/
};
class Children : public Parents{
    /*codes here*/
};
int main(){
    Children * daughter = new Children();
    Parents * mother = static_cast<Parents*> (daughter); //right, cast with polymorphism    
    Parents * father = new Parents();
    Children * son = static_cast<Children*> (father); //no error, but not safe
}
    2 基本数据类型之间的转换也是不安全的
#include <iostream>
using namespace std;
int main(){
        float floatvalue=21.7;
        int intvalue=7;
        cout<<floatvalue/7<<"\t\t"<<static_cast<int>(floatvalue)/7<<endl;
        cout<<intvalue/3<<"\t\t"<<static_cast<float>(intvalue)/3<<endl;
}
运行结果:
3.1        3
2        2.33333
    3 把空指针转换成目标类型的空指针
    4 把任何类型的表达式转换成void类型
#include <iostream>
using namespace std;
int main(){
        int a=100;
        float b=12.3456;
        cout<<"static_cast<int>(b)"<<static_cast<int>(b)<<endl;
        cout<<"static_cast<float>(a)"<<static_cast<float>(a)<<endl;
//      int* ip=&a;
//      float* fb=static_cast<float*>(ip);//error       
        void* p=&a;
        float* f_p=static_cast<float*>(p);
        cout<<"*f_p:"<<*f_p<<endl;
}
static不能转换掉expression的const volitale或者_unaligned属性
注意:不相关的类型之间的转换在static中是不可以的:
class CBaseX{
public:
    int x;
    CBaseX(){ 
        x = 10; 
    }
    void foo(){ 
        printf("CBaseX::foo() x=%d ", x); 
    }
};
class CBaseY{
public:
    int y;
    int* py;
    CBaseY(){ 
        y = 20; 
        py = &y; 
    }
    void bar(){ 
        printf("CBaseY::bar() y=%d, *py=%d ", y, *py); 
    }
};
class CDerived : public CBaseX, public CBaseY{
public:
    int z;
};
int main(){
    CBaseX *pX = new CBaseX();
    CBaseY *pY1 = static_cast<CBaseY*>(pX); //错误不能将CBaseX*转换成CBaseY*
    CBaseX *pX = new CBaseX();
    CBaseY *pY1 = reinterpret_cast<CBaseY*>(pX); //正确. “欺骗”编译器
    pY1->bar(); //崩溃
//正如我们在泛型例子中所认识到的,如果你尝试转换一个对象到另一个无关的类static_cast<>将失败,而reinterpret_cast<>就总是成功“欺骗”.
}


原创粉丝点击