(创建于2017/12/31)
C++类型转换
static_cast:静态类型转换,编译时c++编译器会做类型检查,可以用于转换基本类型,不能转换指针类型,否则编译器会报错
reinterpret_cast 可用于函数指针转换,进行强制类型转换,重新解释
上边两个基本上把c语言的强制类型转换覆盖完了
const_cast 去除变量的只读属性
dynamic_cast 动态类型转换,安全的基类和子类之间的转换,运行时类型检查
1.static_cast 基本类型转换
#include <iostream>
using namespace std;
void main() {
double a = 10.2324;
int b = static_cast<int>(a);
cout << a << endl;
cout << b << endl;
system("pause");
}
- const_cast 去常量
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
void func(const char c[]) {
//c[1] = 'a';
//通过指针间接赋值
//其他人并不知道,这次转型是为了去常量
//char* c_p = (char*)c;
//c_p[1] = 'X';
//提高了可读性
char* c_p = const_cast<char*>(c);
c_p[1] = 'Y';
cout << c << endl;
}
void main() {
//转换成功
char c[] = "hello";
func(c);
//无法转换
const char* c= "hello world";
char* p = const_cast<char*>(c);
p[0] = 'a';
cout << c << endl;
cout << p << endl;
system("pause");
}
3.dynamic_cast 子类类型转为父类类型
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");
}
4.reinterpret_cast 函数指针转型,不具备移植性
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
void main() {
char* p =new char[10];
strcpy(p, "today is a good day");
//编译提示 “static_cast” : 无法从“char * ”转换为“int* ”
//int* p1 = static_cast<int*>(p);
int* p2 = reinterpret_cast<int*>(p);
cout << p << endl;
cout << p2 << endl;
system("pause");
}
打印结果
today is a good day
0141DC08
请按任意键继续. . .