C++中类型转换一般这样写
double double_age = 13.9;
int int_age = int(age);
// int int_age = (int)double_age; //也可以这样写
// int int_age = (int)(double_age); //也可以这样写
// int int_age = ((int)(double_age)); //当然也可以这样写,只要您不觉得累
但是今天讲的是强制类型转换
https://cplusplus.com/doc/tutorial/typecasting/
dynamic_cast
(expression)
reinterpret_cast(expression)
static_cast(expression)
const_cast(expression)
如果父类指针强制转换为子类,dynamic_cast转换判断出不安全,会获得空指针。
// dynamic_cast
#include
#include
using namespace std;
class Base { virtual void dummy() {} };
class Derived: public Base { int a; };
int main () {
try {
Base * pba = new Derived;
Base * pbb = new Base;
Derived * pd;
pd = dynamic_cast<Derived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast.\n";
pd = dynamic_cast<Derived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast.\n";
} catch (exception& e) {cout << "Exception: " << e.what();}
二进制内存形式的强制转换
class A { /* ... */ };
class B { /* ... */ };
A * a = new A;
B * b = reinterpret_cast(a);
显示类型转换
class Base {};
class Derived: public Base {};
Base * a = new Base;
Derived * b = static_cast<Derived*>(a)
const_cast可以用于const关键字的去除
// const_cast
#include
using namespace std;
void print (char * str)
{
cout << str << '\n';
}
int main () {
const char * c = "sample text";
print ( const_cast<char *> (c) );
return 0;
}