static_cast的用武之地

static_cast只能进行基本类型之间的转换吗?

#include <iostream>
using namespace std;

typedef struct  {
	int a;
} Base;

typedef struct  _Drive: public Base {
	int stSMacDB;
} Drive;

int main()
{
	// 基本类型转换
	double dpi = 3.1415;
	// int num1 = dpi;//默认自动类型转换,会提示 warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data
	int num2 = static_cast<int>(dpi);//静态类型转换,在编译时会做类型检查,如有错误会提示

	// 指针转换
	// char* -> int*
	char a = 1;
	char* p1 = &a;
	int b = 10;
	int* p2 = &b;
	//p2 = static_cast<int*>(p1);// error C2440: 'static_cast' : cannot convert from 'char *' to 'int *'
	// p2 = reinterpret_cast<int *>(p1);// OK
    void* p3 = p2; // OK 
	// int *p4 = p3; // error C2440: 'initializing' : cannot convert from 'void *' to 'int *'
	int *p4 = static_cast<int*>(p3);
	
	
	Drive dv;
	Base *pB = &dv;
	// 下行转换
	Drive *pD = static_cast<Drive*>(pB); // OK
	// Drive *pD = dynamic_cast<Drive*>(pB); // error C2683: 'dynamic_cast' : 'Base' is not a polymorphic type
	// Drive *pD = pB; // error C2440: 'initializing' : cannot convert from 'Base *' to 'Drive *'

	// 上行转换
	Drive *pD2 = &dv;
	Base *pB2 = pD2; // OK


	return 0;
}

  

// 综上所述,static_cast的可以办到如下事情:
// 1、基本类型间的转换
// 2、void*指针转换成其他指针类型,其他类型向void*指针转换不需要强转【函数指针例外,函数指针不支持隐式转换成void*】
// 3、非多态类(没有虚函数的类)的下行转换(父类向子类的转换),上行转换是安全的,不需要强转。如果是多态类,使用dynamic_cast下行转换

posted @ 2020-02-10 17:21  ren_zhg1992  阅读(188)  评论(0)    收藏  举报