• dynamic_caast操作符


    dynamic_caast操作符,将基类的指针或引用安全的转换为派生类的指针或引用。

    原理:

      将一个基类对象指针或引用抛到继承类指针,dynamic_cast会根据基类指针是否真正指向继承类指针来做相应处理

    返回值 :

      指针的动态转型:

          -正确执行时,结果为指向目标类对象的指针

          -错误执行时,结果为0/null (C++ 11 :nullptr)

      引用的动态转型:

          -正确执行时,结果为目标类的引用

          -错误执行时,引发bad_cast异常

    注意:

      dynamic_cast在将父类cast到子类时,父类必须要有虚函数。

    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    #include<typeinfo>
    using namespace std;
    
    
    class Employee {
    public:
        virtual void PaySalary();
        virtual void PayBonus()
            ;
    };
    
    class Manager :public Employee {    //公有继承Employee
    public:
        void PaySalary() override;
        void PayBonus() override;
    };
    
    class Programmer :public Employee {
    public:
        void PaySalary() override;
        void PayBonus() override;
    };
    
    class Company {
    public:
        virtual void PayRoll(Employee *e);
        virtual void PayRoll(Employee &e);
    private:
        vector<Employee *> _employees;
    };
    /*
    void Company::PayRoll(Employee *e) {
        e->PaySalary();
        e->PayBonus();
    }
    */
    void Company::PayRoll(Employee *e) { //版本二
        Programmer *p = dynamic_cast<Programmer *>(e);
        if (p) {
            p->PayBonus();
            p->PaySalary();
        }
        else //不发奖金
            e->PaySalary();
    }
    void Company::PayRoll(Employee &e) { //版本二
        try {
            Programmer &p = dynamic_cast<Programmer&>(e);
            p.PaySalary();
            p.PayBonus();
        }
        catch (bad_cast) {
            e.PaySalary();
        }
    }
    
    int main()
    {
        return 0;
    }

     static_cast 静态类型的用途

       与dynamic_cast不同,static_cast不仅可用于指针和引用,还可以用于其他型式

      一般用于非类型式的普通数据对象转型

      不进行运行期型式检查,不安全

      若转型失败,结果无定义

    const_cast 常量转型

      用于取消或设置量的const状态(比如改变const的值,或者取消量的const状态,或者把一个量设置为const)

      //

      如果原始数据对象不能写入,则取消常量修饰可以能会导致未知结果

    class ConstCastTest {
    public:
        void SetNum(int _num) {
            num = _num;
        }
        void PrintNum() const;
    private:
        int num;
    };
    void ConstCastTest::PrintNum() const {
        //临时取消常量约束,修改目标对象的内容
        const_cast<ConstCastTest *>(this)->num--;
        cout << num << endl;
    }
  • 相关阅读:
    SentiAnalysis
    大数据索引技术 B+ tree vs LSM tree
    Regression, 回归问题
    Data Mining with R
    Why Vector Clock are Easy or Hard?
    How to know what an HRESULT code means?
    如何判断数据库表的某个列上有重复值的记录存在?
    关于SharePoint 2010里Servers in farm页面里status意义的澄清
    SharePoint Security系列 之二 CrossSite Request Forgery
    从MOSS2007升级到SharePoint2010后Report Server content types升级失败
  • 原文地址:https://www.cnblogs.com/hutonm/p/6830030.html
Copyright © 2020-2023  润新知