利用案例简要阐述C++的强制类型转换

C语言的风格: type b = (type) a;

C++语言风格:type b = 转换形式 <type> (a);

四种形式的介绍:

  • static_cast 静态类型转化(让C++编译器在编译时进行类型检查)
  • reinterpreter_cast重新解释类型
  • dynamic_cast命名上理解是动态类型转换,如子类和父类之间的多态类型转换
  • const_cast 字面上理解就是去const属性

案例一:主要进行解释dynamic_cast

 

#include <iostream>
using namespace std;

class Animal
{
public:
    virtual void cry() = 0;
};

class Dog:public Animal
{
public:
    virtual void cry()
    {
        cout << "wang wang" << endl;
    }
    void doHome()
    {
        cout << "watch door" << endl;
    }
};

class Cat:public Animal
{
public:
    virtual void cry()
    {
        cout << "miao miao" << endl;
    }
    void catchMouse()
    {
        cout << "catch mouse" << endl;
    }
};

void playObj(Animal* base)
{
    base->cry();
    Dog* d;
    d = dynamic_cast<Dog*>(base);
    if (d != NULL)
    {
        d->doHome();
    }

    Cat* c;
    c = dynamic_cast<Cat*>(base);
    if (c != NULL)
    {
        c->catchMouse();
    }

}

int main()
{
    Dog d;
    Cat c;
    /*
    playObj(&d);
    playObj(&c);
    */

    Animal* a;
    a = static_cast<Animal*>(&d);
    a->cry();
    return 0;
}

 

案例二:主要解释const_cast 

#include <iostream>
using namespace std;

void stringPlay(const char *p)
{
    char* pBuf;
    pBuf = const_cast<char *>(p);
    pBuf[0] = 'Z';
}

int main()
{
    char p[] = "abcdefghijk"; //已经分配空间
    stringPlay(p);
    cout << p << endl;

    const char *newP = "abcdefgh"; 
    /*
    newP这是指向一个字符串常量,所以char *newP = "abcdefgh";会出现语法错误,
    没有给newP分配空间,所以不能调用上面的方法
    */

    return 0;
}

详细解释可以参考:https://www.cnblogs.com/Allen-rg/p/6999360.html

 

转载于:https://www.cnblogs.com/qkqBeer/articles/10808754.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值