START
Hi,大家好!我们知道自C++11开始,C++引入了四种类型转换方式。C语言中的强制类型转换,可以在任意类型之间转换。这种强制转换很不不安全。C++中如果采用C中的强制类型转换,例如很可能我们编写代码时疏忽的将指向const对象的指针转换成非const对象的指针,或者可能将基类对象指针转成了派生类对象的指针,这种方式在C++中有很大隐患。所以C++中引入了以下四种方式。
这四种类型转换方式:
在 C++ 中,主要的类型转换方式,它们分别是:
静态转换(Static Cast):
double myDouble = 3.14;
int myInt = static_cast<int>(myDouble);
static_cast
关键字。动态转换(Dynamic Cast):
class Base {
virtual void foo() {}
};
class Derived : public Base {
};
Base* basePtr = new Derived;
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
// 转换成功
} else {
// 转换失败
}
dynamic_cast
关键字。常量转换(Const Cast):
const int myConstInt = 42;
int* myMutableInt = const_cast<int*>(&myConstInt);
*myMutableInt = 100; // 此时修改了原本为常量的值
const_cast
关键字。const
修饰符。重新解释转换(Reinterpret Cast):
int myInt = 42;
double* myDoublePtr = reinterpret_cast<double*>(&myInt);
reinterpret_cast
关键字。