c++强制类型转换:

强制类型转换:
1. const属性用const_cast。
案例:

说明:该变量可以将变量的const 的属性去掉。如该案例,转换后修改x的值是合法的。

2. 基本类型转换用static_cast。
案例:

说明:一般用在(1)基本类型,(2)用父类和子类也是可以的。

3. 多态类之间的类型转换用dynamic_cast(显示转换,运行时检查,保证转换的安全)。
案例:

#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;

class Animal {
public:
    virtual void makeSound() {
        cout << "Animal is making a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        cout << "Dog is barking" << endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        cout << "Cat is meowing" << endl;
    }
};


int main() {
    Animal* animal = new Dog();
    animal->makeSound();

    Dog* dog = dynamic_cast<Dog*>(animal);
    if (dog) {
        cout << "Animal is a dog" << endl;
        dog->makeSound();
    } else {
        cout << "Animal is not a dog" << endl;
    }

    //Cat* cat = dynamic_cast<Cat*>(animal);  // 转换将会失败,cat 为null,猫不是狗,附和逻辑,类型安全。
    Cat* cat = static_cast<Cat*>(animal);  // 转换成功,cat 不为空,猫是狗,类型不安全。
    if (cat) {
        cout << "Animal is a cat" << endl;
        cat->makeSound();
    } else {
        cout << "Animal is not a cat" << endl;
    }

    delete animal;
    return 0;
}

说明:
(1)如果继承中用到了多态(基类函数 带virtual),则相关的基类和子类之间的转换则用dynamic_cast. 不要用static_cast。

4. 不同类型的指针类型转换reinterpreter_cast
 这个关键字用的很少,不在这里介绍。

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值