09.C++类型转换

本文详细介绍了C++中四种类型转换的方式:static_cast、const_cast、dynamic_cast和reinterpret_cast的具体应用场景及注意事项。从基本概念出发,通过实例演示了每种转换方式的特点与使用场合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(创建于2017/12/31)

C++类型转换

    static_cast 普遍情况
    const_cast 去常量
    dynamic_cast 子类类型转为父类类型
    reinterpret_cast 函数指针转型,不具备移植性

1.static_cast 普遍情况

#include <iostream>

using namespace std;
//原始类型转换,所有情况都是一种写法,可读性不高,有可能有潜在的风险

void* func(int type){   
    switch (type){
    case 1: {
        int i = 9;
        return &i;
    }
    case 2: {
        int a = 'X';
        return &a;
    }
    default:{
        return NULL;
    }

    }   
}

void func2(char* c_p){
    cout << *c_p << endl;
}

void main(){    
    //int i = 0;
    //自动转换
    //double d = i;
    //double d = 9.5;
    //int i = d;

    //int i = 8;
    //double d = 9.5;
    //i = static_cast<int>(d);
    
    //void* -> char*
    //char* c_p = (char*)func(2);
    //char* c_p = static_cast<char*>(func(2));

    //C++ 意图明显
    func2(static_cast<char*>(func(2)));
    //C
    func2((char*)(func(2)));
    
    system("pause");
}
  1. const_cast 去常量
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);

    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 函数指针转型,不具备移植性

void func1(){
    cout << "func1" << endl;
}

char* func2(){
    cout << "func2" << endl;
    return "abc";
}

typedef void(*f_p)();

void main(){
    //函数指针数组
    f_p f_array[6];
    //赋值
    f_array[0] = func1;

    //C方式
    //f_array[1] = (f_p)(func2);
    //C++方式
    f_array[1] = reinterpret_cast<f_p>(func2);

    f_array[1]();

    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值