#include <iostream>
using namespace std;
class A
{
public:
operator int() {return 1;}
operator char * () {return NULL;}
virtual ~A(){}
};
class B:public A
{
};
int
main(int argc, char * argv[])
{
A a;
int n;
char * p = "China Linux";
/*
static_cast用来进行自然的低风险的转换。如int型和char型之间的转换、int型与char型的转换。
static_cast不能用来在不同类型间进行强制转换,也不能用来在整型与指针间进行转换。
n = static_cast<int>(p); //编译错误
p = static_cast<char *>(n); //编译错误
*/
n = static_cast<int>(3.14);
n = static_cast<int>(a);
p = static_cast<char*>(a);
/*
reinterpret_cast用来进行不同类型的指针与引用之间的转换。也可以用来在指针与整型数之间的转换。
*/
n = reinterpret_cast<int>(p);
/*
const_cast用来去除const属性
*/
const int pp = 5;
int & b = const_cast<int&>(pp);
b = 10;
/*
dynamic_cast在将基类指针转化为派生类指针时,会进行安全性检查。
*/
A aa;
B * pB = dynamic_cast<B*>(&aa);
if(pB == NULL)
cout << "转换失败" << endl;
return 0;
}
关于dynamic_cast,我另外测试了一下
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class Base{ public: virtual ~Base(){} };
class Derive1 : public Base{};
class Derive2 : public Base{};
int main(int argc, char * argv[])
{
Derive1 d1;
Derive2 d2;
Derive1 * p1;
Derive2 * p2;
Base & refBase = d1;
Base * pBase = &d1;
p2 = dynamic_cast<Derive2*>(pBase);
if(p2 == NULL)
cout << "unsafe convertion" << endl;
p1 = dynamic_cast<Derive1*>(pBase);
if(p1 == NULL)
cout << "unsafe convertion" << endl;
try{
Derive2 & ref2 = dynamic_cast<Derive2&>(refBase);
}catch(exception & e)
{
cout << e.what() << endl;
}
return 0;
}