zoukankan      html  css  js  c++  java
  • C++ 四种cast 的使用场景

    简介

    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!!
    ";
        }
        ~Father(){}
        virtual void print(){
            cout<<"FFFF
    ";
        }
    };
    
    class Son : public Father{
    public:
        Son() {
            cout << "I'am Son!!
    ";
        }
        ~Son(){}
        void print(){
            cout<<"SSSS
    ";
        }
    };
    
    
    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;
    }
    
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    Docker基本命令及工作原理
    Docker安装
    linux命令
    MTPuTTy使用
    SpringBoot--swagger搭建、配置及使用
    idea使用技巧
    Idea插件
    IDEA开发工具使用 git 创建项目、拉取分支、合并分支
    git命令
    javbus爬虫-老司机你值得拥有
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/15183911.html
Copyright © 2011-2022 走看看