C++(四十五) — 类型转换(static_cast、dynamic_cast 、const_cast、reinterpreter_cast)

 0、总结

  (1)要转换的变量,转换前、转换后、转换后的结果。

  (2)一般情况下,避免进行类型转换。

1、_static_cast(静态类型转换,int 转换为char)

   格式:TYPE B = static_cast<TYPE>(a)

   reinterpreter_cast(重新解释类型):专门用于指针类型的转换。

void main()
{
    double dpi = 3.1415;
    //int num1 = dpi;//默认自动类型转换,会提示 warning
    int num2 = static_cast<int>(dpi);//静态类型转换,在编译时会做类型检查,如有错误会提示

    // char* -> int*
    char* p1 = "hello";
    int* p2 = nullptr;
    //p2 = static_cast<int*>(dpi);// 转换类型无效,
    p2 = reinterpret_cast<int *>(p1);//相当于强制类型转化,指针类型
    cout << p1 << endl;//输出字符串
    cout << p2 << endl;//输出指针的首地址

    system("pause");
}

 

2、dynamic_cast(动态类型转化,如子类和父类之间的多态类型转换)

#include <iostream>
using namespace std;

class Animal
{
public:
    virtual void cry() = 0;
};
class Dog :public Animal
{
public:
    virtual void cry()
    {
        cout << "wangwang" << endl;
    }
    void doHome()
    {
        cout << "kanjia" << endl;
    }
};
class Cat :public Animal
{
public:
    virtual void cry()
    {
        cout << "miaomiao" << endl;
    }
    void doHome()
    {
        cout << "keai" << endl;
    }
};
void playObj(Animal *base)
{
    base->cry();
    //运行时的类型识别,
    //父类对象转换为子类对象
    Dog *pDog = dynamic_cast<Dog*>(base);//如果不是该类型,则返回值为null
    if (pDog != NULL)
    {
        pDog->doHome();
    }
    Cat *pCat = dynamic_cast<Cat*>(base);//如果不是该类型,则返回值为null
    if (pCat != NULL)
    {
        pCat->doHome();
    }
}

void main()
{
    Dog d1;
    Cat c1;
    //父类对象转换为子类对象
    playObj(&d1);
    playObj(&c1);
    //子类对象转换为父类对象
    Animal *pBase = nullptr;
    pBase = &d1;
    pBase = static_cast<Animal *>(&d1);

    system("pause");
}

 

3、const_cast(去 const 属性)

   该函数把只读属性去除。

p1 = const_cast<char*>(p);

 

posted @ 2019-06-07 11:08  深度机器学习  阅读(3775)  评论(0编辑  收藏  举报