1-static_cast.cpp
#include <iostream>
using namespace std;
class Parent
{
};
class Child : public Parent
{
};
int main()
{
int a = 1;
char ch = 'x';
a = static_cast<int>(ch); //用于普通类型之间的转换
//int *p = static_cast<int *>(&ch); //不能用于普通类型指针之间的转换
Parent p;
Child c;
p = static_cast<Parent>(c); //用于有继承关系的类对象之间的转换
Parent *p1 = static_cast<Parent *>(&c); //用于类对象指针之间的转换
return 0;
}
2-reinterpret_cast.cpp
#include <iostream>
using namespace std;
int main()
{
int b = 10;
int a = 100;
char *p = reinterpret_cast<char *>(&a); //用于普通累心指针之间的转换(不安全)
cout << *(p + 1) << endl;
cout << *(&a + 1) << endl;
int *q = reinterpret_cast<int *>(100); //用于数字和指针之间的转换(很容易出现野指针)
*q = 1;
return 0;
}
3-const_cast.cpp
#include <iostream>
using namespace std;
int main()
{
const int a = 1; //常量
int *p = const_cast<int *>(&a);
*p = 100;
cout << a << endl;
const int &m = 1;
int &n = const_cast<int &>(m);
n = 100;
cout << m << endl;
cout << n << endl;
const int x = 1;
int &y = const_cast<int &>(x);
y = 100;
cout << x << endl;
cout << y << endl;
return 0;
}
4-dynamic_cast.cpp
#include <iostream>
using namespace std;
class Parent
{
public:
virtual void f()
{
}
};
class Child : public Parent
{
public:
void f()
{
}
};
int main()
{
Child *c = new Child;
delete c;
c = static_cast<Child *>(new Parent); //派生类指针指向基类对象(错误)
c = dynamic_cast<Child *>(new Parent); //运行的时候做类型检查,如果不能转换,则返回NULL,比static_cast安全
if (NULL == c)
{
cout << "强转失败" << endl;
}
else
{
cout << "强转成功" << endl;
delete c;
}
return 0;
}