09.C++类型转换

(创建于2017/12/31)

C++类型转换

static_cast:静态类型转换,编译时c++编译器会做类型检查,可以用于转换基本类型,不能转换指针类型,否则编译器会报错
reinterpret_cast 可用于函数指针转换,进行强制类型转换,重新解释

上边两个基本上把c语言的强制类型转换覆盖完了

const_cast 去除变量的只读属性
dynamic_cast 动态类型转换,安全的基类和子类之间的转换,运行时类型检查

1.static_cast 基本类型转换

#include <iostream>

using namespace std;


void main() {
    double a = 10.2324;
    int b = static_cast<int>(a);
    cout << a << endl;
    cout << b << endl;
    system("pause");
}
  1. const_cast 去常量
#define   _CRT_SECURE_NO_WARNINGS 
#include <iostream>

using namespace std;


void func(const char c[]) {
    //c[1] = 'a';
    //通过指针间接赋值
    //其他人并不知道,这次转型是为了去常量
    //char* c_p = (char*)c;
    //c_p[1] = 'X';
    //提高了可读性
    char* c_p = const_cast<char*>(c);
    c_p[1] = 'Y';

    cout << c << endl;
}

void main() {
    //转换成功
    char c[] = "hello";
    func(c);

    //无法转换
    const char* c= "hello world";
    char* p = const_cast<char*>(c);
    p[0] = 'a';
    cout << c << endl;
    cout << p << endl;

    system("pause");
}

3.dynamic_cast 子类类型转为父类类型

class Person{
public:
    virtual void print(){
        cout << "人" << endl;
    }
};

class Man : public Person{
public:
    void print(){
        cout << "男人" << endl;
    }

    void chasing(){
        cout << "泡妞" << endl;
    }
};


class Woman : public Person{
public:
    void print(){
        cout << "女人" << endl;
    }

    void carebaby(){
        cout << "生孩子" << endl;
    }
};

void func(Person* obj){ 

    //调用子类的特有的函数,转为实际类型
    //并不知道转型失败
    //Man* m = (Man*)obj;
    //m->print();

    //转型失败,返回NULL
    Man* m = dynamic_cast<Man*>(obj);   
    if (m != NULL){
        m->chasing();
    }

    Woman* w = dynamic_cast<Woman*>(obj);
    if (w != NULL){
        w->carebaby();
    }
}

void main(){
    
    Woman w1;
    Person *p1 = &w1;

    func(p1);

    system("pause");
}

4.reinterpret_cast 函数指针转型,不具备移植性

#define   _CRT_SECURE_NO_WARNINGS 
#include <iostream>

using namespace std;


void main() {
    char* p =new char[10];
    strcpy(p, "today is a good day");
    //编译提示 “static_cast” : 无法从“char * ”转换为“int* ”
    //int* p1 = static_cast<int*>(p);
    int* p2 = reinterpret_cast<int*>(p);
    cout << p << endl;
    cout << p2 << endl;
    system("pause");
}

打印结果
today is a good day
0141DC08
请按任意键继续. . .

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这篇文章也许会持续更新,也欢迎大家提出问题,一起探讨。原文地址AC4Fun,转载请注明出处。 **********...
    羲牧阅读 4,890评论 7 23
  • 文章转载自c的四种类型转换 使用标准C++的类型转换符:static_cast、dynamic_cast、rein...
    Yihulee阅读 1,421评论 0 1
  • 前言 把《C++ Primer》[https://book.douban.com/subject/25708312...
    尤汐Yogy阅读 9,554评论 1 51
  • 隐式类型转换: C++的隐式转换发生在以下四种情况: 在混合类型的算术表达式中。 在表达式赋值中。 表达式传给函数...
    CapJon阅读 668评论 1 2
  • C++类型转换总结 本章内容:1 前言2 static_cast3 dynamic_cast4 const_cas...
    Haley_2013阅读 969评论 0 50