一.C方式的强制类型转换
(Type)(Expression)
#include <stdio.h>
typedef void(PF)(int);
struct Point
{
int x;
int y;
};
int main()
{
int v = 0x12345;
PF* pf = (PF*)v;
char c = char(v);
Point* p = (Point*)v;
pf(5);
printf("p->x = %d\n", p->x);
printf("p->y = %d\n", p->y);
return 0;
}
运行结果:
段错误
- C方式强制类型转换存在的问题
(1)过于粗暴
任意类型之间都可以进行转换,编译器很难判断其正确性
(2)难于定位
在源码中无法快速定位所有使用强制类型转换的语句
二.C++将强制类型转换分为4种不同的类型:
static_cast
const_cast
dynamic_cast
reinterpret_cast
用法:xxx_cast < Type > (Expression)
static_cast强制类型转换:
(1)用于基本类型间的转换 (int, double, float …)
(2)不能用于基本类型指针间的转换
(3)用于有继承关系类对象之间的转换和类指针之间的转换
const_cast强制类型转换:
(1)用于去除变量的只读属性
(2)强制转换的目标类型必须是指针或引用
reinterpret_cast强制类型转换:
(1)用于指针类型间的强制转换(重解释,将一个指针类型解释成另外一个指针)
(2)用于整数和指针类型间的强制转换
dynamic_cast强制类型转换:
(1)用于有继承关系的类指针间的转换
(2)用于有交叉关系的类指针间的转换
(3)具有类型检查的功能
(4)需要虚函数的支持
支持动态类型识别
#include <stdio.h>
void static_cast_demo()
{
int i = 0x12345;
char c = 'c';
int* pi = &i;
char* pc = &c;
c = static_cast<char>(i);
// pc = static_cast<char*>(pi); // Error
}
void const_cast_demo()
{
const int& j = 1; //定义了只读变量j
int& k = const_cast<int&>(j); //去掉j的只读属性,K可以修改j的值
const int x = 2; //定义了常量x
int& y = const_cast<int&>(x); //为真正意义的常量分配内存空间,y是内存空间的别名
// int z = const_cast<int>(x); // Error,只能用于引用或指针
k = 5;
printf("k = %d\n", k);
printf("j = %d\n", j);
y = 8;
printf("x = %d\n", x);
printf("y = %d\n", y);
printf("&x = %p\n", &x);
printf("&y = %p\n", &y);
}
void reinterpret_cast_demo()
{
int i = 0;
char c = 'c';
int* pi = &i;
char* pc = &c;
pc = reinterpret_cast<char*>(pi);
pi = reinterpret_cast<int*>(pc);
pi = reinterpret_cast<int*>(i);
//c = reinterpret_cast<char>(i); // Error,不能在基本类型间转换
}
void dynamic_cast_demo()
{
int i = 0;
int* pi = &i;
//char* pc = dynamic_cast<char*>(pi); // Error,不是类指针间的转换,没有虚函数
}
int main()
{
static_cast_demo();
const_cast_demo();
reinterpret_cast_demo();
dynamic_cast_demo();
return 0;
}
运行结果:
k = 5
j = 5
x = 2
y = 8
&x = 0019FB04
&y = 0019FB04
三.问题深入探讨
问题一:继承中如何正确使用强制类型转换?
- dynamic_cast是与继承相关的类型转换关键字
- dynamic_cast要求相关的类中必须有虚函数
- 用于有直接或者间接继承关系的指针(引用)之间:
(1)指针
转换成功:得到目标类型的指针
转换失败:得到一个空指针
(2)引用
转换成功:得到目标类型的引用
转换失败:得到一个异常操作信息
编译器会检查dynamic_cast的使用是否正确
类型转换的结果只可能在运行阶段才能得到
dynamic_cast示例:
#include <iostream>
#include <string>
using namespace std;
class Base {
public:
Base() {
cout << "Base::Base()" << endl;
}
virtual ~Base() { //类中有虚函数才能使用dynamic_cast
cout << "Base::~Base()" << endl;
}
};
class Derived : public Base
{
};
int main() {
Base* p = new Derived; //父类指针p指向子类对象
Derived* pd = dynamic_cast<Derived*>(p); //使用p指针直接初始化pd,需要虚函数
cout << "pd = " << pd << endl;
delete p;
return 0;
}
编译结果:
Base::Base()
pd = 0x93829443
Base::~Base()
int main() {
Base* p = new Base; //父类指针p指针指向父类的对象
Derived* pd = dynamic_cast<Derived*>(p);
if( pd != NULL ) {
cout << "pd = " << pd << endl;
} else {
cout << "Cast error!" << endl;
}
delete p;
return 0;
}
运行结果
Base::Base()
Cast error! //打印Cast error的原因:不能用子类的指针指向一个父类的对象
Base::~Base()