C/C++: C++ 中 static_cast 类型转换的含义

来源:互联网 发布:mac如何安装mysql 编辑:程序博客网 时间:2024/05/05 01:40

摘自: C++编程思想 : static_cast可以用于所有良定义转换。这些包括“安全”转换与次安全转换, “安全”转换 是编译器允许我们不用映射就能完成的转换。次安全转换也是良定义的。由 s t a t i c _ c a s t覆盖的变换的类型包括典型的无映射变换、窄化变换(丢失信息)用void*的强制变换、隐式类型变换和类层次的静态导航。


简单点说就是, static_cast 是温柔的,靠谱的,能做好的事情肯定能给你做,做不来的你别求他, 求也没用,别勉强。



#include <iostream>
using namespace std;

class base {};


class derived: public base
{
public:
    operator int() {return 1;}
};

void func(int){}

class other {};





int main()
{
    int i = 0x7fff;
    long l;
    float f;


    l = i;
    f = i;

    l = static_cast<long>(i);
    f = static_cast<float>(i);

    i = l;
    i = f;

    i = static_cast<int>(l);
    i = static_cast<char>(i);

    char c = static_cast<char>(i); //warning


    void *vp = &i;

    float *fp = (float *)vp;
    fp = static_cast<float *>(vp);

    derived d;
    base *bp = &d;

    bp = static_cast<base*>(&d);


    int x = d;

    x = static_cast<int>(d);

    func(d);
    func(static_cast<int>(d));


    derived* dp = static_cast<derived*>(bp);

    //other *op = static_cast<other *>(bp);

    other* op2 = (other*)bp;

    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}



0 0
原创粉丝点击