cpp的类型转换
为什么需要类型转换运算符
类型转换时一种机制,让程序猿能够暂时或者永久的改变对对象的解释
传统的c风格类型转换
int b = 11;
float a = (float) b;
4个类型转换运算符
4个运算符,也是双刃剑哦,
static_cast, 编译阶段的检测,运行阶段不检测
dynamic_cast,编译阶段的不检测,运行阶段检测,运行阶段类型识别
reinterpret_cast 任意转换,最接近c的转换方式的,可能引起混乱
const_cast 关闭对象的const修饰符
简明的代码是最有力的说明哦
//
// main.cpp
// use_cast
//
// Created by bikang on 16/10/25.
// Copyright (c) 2016年 bikang. All rights reserved.
//
#include <iostream>
using namespace std;
class Fathor{
public:
Fathor(){};
~Fathor(){};
};
class Son:public Fathor{
public:
Son(){};
~Son(){};
};
class OtherData{
public:
OtherData(){};
~OtherData(){};
};
class MAnimal{
public:
virtual void speak()=0;
};
class MDog:public MAnimal{
public:
MDog(){ a = 11;}
void speak(){cout << "dog speak" << endl;}
int a;
};
class MCat:public MAnimal{
public:
void speak(){cout << "cat speak" << endl;}
};
void changeDog(const MDog *obj);
//测试cast转换
//static_cast, 编译阶段的检测,运行阶段不检测
//dynamic_cast,编译阶段的不检测,运行阶段检测,运行阶段类型识别
//reinterpret_cast 任意转换,最接近c的转换方式的,可能引起混乱
//const_cast 关闭对象的const修饰符
void tcast();
int main(int argc, const char * argv[]) {
// insert code here...
tcast();
return 0;
}
void tcast(){
cout << "starting cast date" << endl;
//static_cast 编译阶段检测,不会执行任何运行阶段的检查
Fathor *f1 = new Son();
Son *s1 = static_cast<Son*>(f1);
//OtherData *od1 = static_cast<OtherData *>(f1);//error
Fathor *f2 = new Fathor();
Son *s2 = static_cast<Son*>(f2);//ok 实际上是有问题的实现了向上转型
//dynamic_cast 编译阶段不检测,运行阶段检测,可检测是否成功,需要多态才能转换哦
MAnimal *panimal = new MDog();
MDog *pdog = dynamic_cast<MDog*>(panimal);
pdog->speak();
panimal = new MCat();
MCat *pcat = dynamic_cast<MCat*>(panimal);
pcat->speak();
//reinterpret_cast 任意转换,最接近c的转换方式的,可能引起混乱
OtherData *od1 = reinterpret_cast<OtherData *>(pcat);
OtherData *od2 = (OtherData *)pcat;
//const_cast 关闭对象的const修饰符,对本来封装好的函数的对象进行修改,可能会引起问题哦
cout << "修改前:"<< pdog->a <<endl;
changeDog(pdog);
cout << "修改后:"<< pdog->a <<endl;
delete od1;
delete s1;
delete s2;
}
void changeDog(const MDog *obj){
MDog *refdata = const_cast<MDog *>(obj);
refdata->a += 11;//如果没有转换时error的
}