C++ 显示类型转换——4种强制类型转换
强制类型转换,顾名思义,就是将变量或对象通过一定方法显示地进行类型转换的措施。强制类型转换并不改变原对象类型,只是通过原对象生成新的对象。在 C++ 中,一共有 4 种强制类型转换的操作,其分别是:static_cast<newType>
,const_cast<newType>
, reinterpret_cast<newType>
及dymatic_cast<newType>
,其分别用于不同的情况下。
1. static_cast<newType>
- 用于任何具有明确定义的类型转换,但是无法去掉底层 const (可以加上底层 const)。
- 用于编译器无法自动执行的类型转换。
首先来看第一点,C++中包含的类型分为指针,内置算术类型及自定义类型,指针不具有明确定义的类型转换,内置算术类型具有明确定义的类型转换,而自定义类型需要借助可以只传递一个参数的构造函数,或者类型转换运算符来具有明确定义的类型转换。
例 1 内置算术强制类型转换
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int value = 5;
cout << typeid(static_cast<double>(value)).name() << endl; // 通过类型转换生成临时变量
cout << typeid(value).name() << endl; // 原对象
return 0;
}
结果如下:
例 2 自定义类型强制类型转换
考虑如下代码,因为没有在 SecondType 中没有可以只接受 FirstType 类型参数的构造函数或者在FirstType 中没有对应的类型转换运算符使得该类型具有明确定义的类型转换,所以无法通过 static_cast<newType>
完成类型转换。
#include <iostream>
#include <typeinfo>
using namespace std;
class FirstType
{
private:
int val_;
};
class SecondType
{
private:
int val_;
};
int main()
{
FirstType firstType;
static_cast<SecondType>(firstType);
return 0;
}
结果如下:
倘若为其加上适当的构造函数或者类型转换运算符,此时该自定义类型便具有明确定义的类型转换,则可实现强制转换的功能:
#include <iostream>
#include <typeinfo>
using namespace std;
class FirstType;
class SecondType
{
public:
SecondType(int val) : val_(val) {
}
explicit SecondType(const FirstType& firsType) : val_(0) {
} // 2 选 1 即可
private:
int val_;
};
class FirstType
{
public:
operator SecondType() const // 2 选 1 即可
{
return SecondType(val_);
}
private:
int val_;
};
int main()
{
FirstType firstType;
cout << typeid(static_cast<SecondType>(firstType)).name() << endl;
return 0;
}
结果如下:
例 3 无法去掉底层const
#include <iostream>
#include <typeinfo>
using