本文最后更新于:2021年2月7日 下午
概览:C++类型转换:static_cast,dynamic_cast,const_cast,reinterpret_cast。
C语言的类型转换
1 2
| int a = 65; char b = (char)a;
|
static_cast转换
- 语法:
type a = static_cast<type>(b);
- 将其他类型的b转换成type类型的a。
- static_cast用于基本数据类型以及有继承关系的子类与父类的指针或者引用之间的类型转换。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class Person {}; class Animal { public: void speak() { cout << "Animal speak" << endl; } }; class Cat :public Animal { public: void speak() { cout << "Cat speak" << endl; } };
void test1() {
int a = 65; char b = static_cast<char>(a); cout << b << endl;
int *ip = new int(3);
Person *person = new Person();
Animal *animal = new Animal(); Cat* cat = static_cast<Cat *>(animal); cat->speak();
Animal row; Animal & ani = row; Cat & meow = static_cast<Cat &>(ani); meow.speak();
}
|
dynamic_cast转换
子类指针转父类指针,是由大到小,是类型安全的。
而父类指针转子类指针,由小到大,是类型不安全的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| class Person {}; class Animal { public: void speak() { cout << "Animal speak" << endl; } }; class Cat :public Animal { public: void speak() { cout << "Cat speak" << endl; } };
void test2() {
Cat* cat = new Cat(); Animal * animal = dynamic_cast<Animal*>(cat); animal->speak();
Cat meow; Cat & ca = meow; Animal & ani = dynamic_cast<Animal &>(ca); ani.speak();
}
|
const_cast转换
- 语法:
type a = dynamic_cast<type * / &>(b);
- 模板参数列表那里要填写指针或者引用。
const_cast用于针对基本数据类型的指针、引用以及自定义类型对象的指针进行const权限的增加或者去除(去除是不改变员数据,会将结果给到一个新的值)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| void test3() {
int a = 10; const int &b = a;
int &c = const_cast<int &>(b); c = 20;
const int &d = const_cast<const int &>(a);
cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; cout << "d = " << d << endl;
a = 10; int *p = &a;
const int * cp = const_cast<const int *>(p);
cout << "*cp = " << *cp << endl;
const int * cp2 = &a;
int *p2 = const_cast<int *>(cp2);
*p2 = 100;
cout << "a = " << a << endl; cout << "*p = " << *p << endl; cout << "*cp = " << *cp << endl; cout << "*cp2 = " << *cp2 << endl; cout << "*p2 = " << *p2 << endl;
}
|
reinterpret_cast 强制类型转换
reinterpret_cast是强制类型转换,任何类型指针都可以转化为其他类型指针。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| void test4() {
Person *person = new Person(); Cat* cat = reinterpret_cast<Cat *>(person); cat->speak();
typedef void(*FUNC1)(int, int); typedef int(*FUNC2)(int, char*);
FUNC1 func1 = nullptr; FUNC2 func2 = reinterpret_cast<FUNC2>(func1); }
|
总结
程序员必须清楚的知道要转变的变量,转换前的类型与转换后的类型,会有什么后果。
一般情况下,不建议类型转换,应当尽量避免类型转换。