C++类型转换
-
static_cast 普遍情况
-
const_cast 去常量
-
dynamic_cast 子类类型转为父类类型(将对象转换为自己的实际类型不成功为NULL)
-
reinterpret_cast 函数指针转型,不具备移植性
-
原始类型转换,所有情况都是一种写法,可读性不高,有可能有潜在的风险
- static_cast 普遍情况
void* func(int type) {
switch (type) {
case 1: {
int i = 9;
return &i;
}
case 2: {
int a = 'X';
return &a;
}
}
return NULL;
}
void func2(char* c_p) {
cout << *c_p << endl;
}
void main() {
int i = 10;
//自动转换
double d = i;
cout << "i=:"<< i << endl;//10
cout << "d=:" << d << endl;//10
double m = 9.5;
int n = m;
cout << "m=:" << m << endl;//9.5
cout << "n=:" << n << endl;//9
double x = 9.5;
int y = 8;
y = static_cast<int>(x);
cout << "y=:" << y << endl;//9
//C语言的类型转换
//char* c_p = (char*)func(2);
//C++的类型转换
char* c_p = static_cast<char*>(func(1));
//C++ 意图明显
func2(static_cast<char*>(func(1)));
//C
func2((char*)(func(2)));
getchar();
}
- const_cast 去常量
void func(const char c[]) {
//c[1] = 'a';//不可以修改
//通过指针间接赋值
//其他人并不知道,这次转型是为了去常量
//char* c_p = (char*)c;
//c_p[1] = 'X';
//提高了可读性
char* c_p = const_cast<char*>(c);//用const_cast来去除const限定
c_p[1] = 'Y';
cout << c << endl;
}
void main() {
char c[] = "hello";
func(c);
system("pause");
}
- dynamic_cast 子类类型转为父类类型(将对象转换为自己的实际类型不成功为NULL)
class Person {
public:
virtual void print() {
cout << "父类" << endl;
}
};
class Man : public Person {
public:
void print() {
cout << "男" << endl;
}
void chasing() {
cout << "那那那那" << endl;
}
};
class Woman : public Person {
public:
void print() {
cout << "女" << endl;
}
void carebaby() {
cout << "啊哈哈哈哈" << endl;
}
};
void func(Person* obj) {
//调用子类的特有的函数,转为实际类型
//并不知道转型失败
//Man* m = (Man*)obj;
//m->print();
//转型失败,返回NULL
Man* m = dynamic_cast<Man*>(obj);
if (m != NULL) {
m->chasing();
}
Woman* w = dynamic_cast<Woman*>(obj);
if (w != NULL) {
w->carebaby();
}
}
void main() {
Woman w1;
Person *p1 = &w1;
func(p1);
system("pause");
}
- reinterpret_cast 函数指针转型,不具备移植性
void func1() {
cout << "func1" << endl;
}
char* func2() {
cout << "func2" << endl;
return const_cast<char*>("abc");
}
typedef void(*f_p)();
void main() {
//函数指针数组
f_p f_array[6];
//赋值
f_array[0] = func1;
//C方式
//f_array[1] = (f_p)(func2);
//C++方式
f_array[1] = reinterpret_cast<f_p>(func2);
f_array[1]();
system("pause");
}
来源:https://blog.csdn.net/huangxiaoguo1/article/details/101036053