c++之旅:类型的强制转换

类型强制转换

在编程的时候我们经常遇到类型的强制转换,C++为此提供了更安全的转换方式,在编程中我们更多的应该采用C++提供的类型转换方式

基本类型转换

基本类型转换用的最多,一般将高精度转换为低精度,static_cast关键字用于基本类型转换。

float a = 1.5;
int b =  static_cast<int>(a);

上面的列子将浮点型转为整型

常量类型转换

常量类型转换一般将指向变量的指针强制让其指向一个常量

const int  a = 1;
const int* p1 = &a;
int* p2 =  const_cast<int*>(&a);

&a的返回值是const int * ,通过**const_cast强制转换为int*类型

普通类型指针转换

使用reinterpret_cast可以将可以实现指向普通类型的指针的类型转换

int a = 0xA0B0C0D0;
char* c =  reinterpret_cast<char*>(&a);
for (int i=0; i<4; i++) {
	printf("%x\n", *(c+i));
}

上的示例中强制让一个char*指针指向了int型的变量,并对变量中的内容进行了访问。

对象指针类型转换

dynamic_csast运算符用于对象的向上转型或向下转型, 其主要用途是确保可以安全地调用虚函数。dynamic_cast的尖括号中必须为指针或者引用。如果是向下转型,其参数中的指针必须要有虚函数,如果转换失败则为NULL

#include <iostream>
#include <string>
using namespace std;

class Person {
    public:
        Person(){};
        virtual ~Person(){cout << "Person" << endl;}
};

class Worker: public Person {
    public:
        Worker(){};
        ~Worker(){cout << "Worker" << endl;}
};

int main(void) {
    Person* person =  dynamic_cast<Person*> (new Worker());
    Worker* worker = dynamic_cast<Worker*>(person);   //传入的person指针对应的类必须要有虚函数
    }

参考

http://www.cnblogs.com/blueoverflow/p/4712369.html

posted @ 2017-05-30 17:26  被罚站的树  阅读(243)  评论(0编辑  收藏  举报