简介

static_cast() : 表示编译级别的强制类型转换, 且不能发现运行是的错误. 类似C的(int) 之类的强制转圈, 不能去除const属性, volatile 属性. 还有一个unaligned属性
dynamic_cast<>() : 运行时检查类型. 主要用于含有虚函数的父类和子类之间的指针转换. 会检查是否能够完成这次转换, 如果不能返回0
const_cast<>(): 作为static_cast的补充, 可以去除const属性
reinterpret_cast<>(): 低层次的类型转换, 可以将指针转为int类型或者long类型.

参考链接

https://blog.csdn.net/ykun089/article/details/106495892
https://www.cnblogs.com/chenyangchun/p/6795923.html

code

class Father{
public:
    Father(){
        cout << "I'am Father!!\n";
    }
    ~Father(){}
    virtual void print(){
        cout<<"FFFF\n";
    }
};

class Son : public Father{
public:
    Son() {
        cout << "I'am Son!!\n";
    }
    ~Son(){}
    void print(){
        cout<<"SSSS\n";
    }
};


int main() {
    const char a = 'a';
    int b = static_cast<char>(a);
    const int g = 20;
    
    int h = static_cast<int>(g);
    // int *h = static_cast<int*>(&g); // 不知道为什么这个const属性会编译出错, 但是上面的不会错误
    cout << "=====================" << endl;
    Father * f = new Son();
    f->print();
    Son *p = dynamic_cast<Son*>(f);
    p->print();
    Father *p1 = dynamic_cast<Father*>(p);
    p1->print();
    cout << "-----------------------" << endl;
    int *h1 = const_cast<int*>(&g); // 去掉const 属性  网站上说去掉const常量const属性
    // 看来const 常量和const属性是不一样的. 比如
    long long gg = 0;
    char * cc = "I love you";
    gg = reinterpret_cast<long long>(cc);
    cout << gg << endl;
}

posted on 2021-08-25 10:39  HDU李少帅  阅读(376)  评论(0)    收藏  举报