c++类型转换

前言:c++提供了四种类型转换,分别是static_cast,reinterpret_cast,dynamic_cast,const_cast。它们都有各自的运用场景.

语法形式(四种都一样):

Type dist = *_cast<Type>(src);

1. static_cast(静态类型转换)

 c/c++中自动类型转换的数据都可以使用static_cast进行转换,这种类型转换使得c++编译器在编译的时候进行类型检查。

代码例子:

#include <iostream>

using namespace std;

void testInt(){
    cout << "double ==> int" <<endl;
    double b = 24.3436546;
    cout << "b:"<< b << endl;
    int a = (int)b; // c语言类型转换
    cout << "c: b ==> a:" << a <<endl;

    int c = static_cast<int>(b);
    cout << "c++: b ==> c:" << c <<endl;
}

void testChar(){
    cout << "int ==> char" <<endl;
    int b = 100;
    cout << "b:"<< b << endl;
    char a = (char)b; // c语言类型转换
    cout << "c: b ==> a:" << a <<endl;

    char c = static_cast<char>(b);
    cout << "c++: b ==> c:" << c <<endl;
}


int main(){
    testInt();
    testChar();
}

2. reinterpret_cast(重新解释类型)

 重新解释类型,有点类似强制转换,如下代码所示:

#include <iostream>

using namespace std;

class Dog{};

class Cat{};

int main(){
    char* p1 = "the world well be wanderful";
    int* p2 = (int*)p1; // c语言类型转换

    //int* p3 = static_cast<int*>(p1);
    int* p3 = reinterpret_cast<int*>(p1);

    cout << "p1:" << p1 <<endl;
    cout << "p2:" << p2 <<endl;
    cout << "p3:" << p3 <<endl;

    Dog* dog = new Dog();
    Cat* cat = reinterpret_cast<Cat*>(dog);
}

3. dynamic_cast(动态类型转换)

 动态类型转换通常用于将父类指针指向的对象(子类)转换成子类对象。在发生动态的情况下可以用于鉴别父类指针指向的对象的具体类别。

如:

#include <iostream>

using namespace std;

class Animal{
public:
    virtual void run(){
        cout << "Animal is runing..." <<endl;
    }
};

class Dog : public Animal{
public:
    void run(){
        cout << "Dog is runing..." <<endl;
    }

    void doHome(){
        cout << "Dog doHome..." <<endl;
    }
};

class Cat : public Animal{
public:
    void run(){
        cout << "Cat is runing..." <<endl;
    }

    void doThing(){
        cout << "猫抓老鼠..." <<endl;
    }
};

void play(Animal* base){
    base->run();
    Dog* dog = dynamic_cast<Dog* >(base);
    if(dog !=NULL){
        dog->doHome();
    }
    Cat* cat = dynamic_cast<Cat* >(base);
    if(cat != NULL){
        cat->doThing();
    }
};

int main(){
    Dog dog;
    Cat cat;
    play(&dog);
    play(&cat);
}

4. const_cast(常量转换)

 可以将const修饰的指针变量转换成普通的指针变量。使用时需要确保指针变量指向的内存空间的值确实能修改,如果不能修改则会报错。

#include <iostream>

using namespace std;

void test(const char* p){
    char* p1 = const_cast<char *>(p);
    p1[3] = 'x';
}

int main(){
    char buf[] = "aaaaaaaaaaaaaaaaaaaaaaaa";
    test(buf);
    cout << buf <<endl;

    char* p = "aaaaaaaaaaaaaaaaaaaaaaaa";
    cout << p <<endl;
    // test(p); // 程序员要确保变量指向的内存空间确实能修改,
    // 如果不能修改会带来灾难性的后果
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值