(1) static_cast
(2) const_cast
(3) dynamic_cast
(4) reinterpret_cast
实例:
// 20145_25_3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//const int *fun(int x,int y)
//{
//}
class Base
{
public:
virtual void m()
{ cout << "This is Base" << endl;};
};
class Derived: public Base
{
public:
void m()
{cout << "This is Derived" << endl;}
void fun()
{ cout << "This is a Derived fun" <<endl;}
};
int _tmain(int argc, _TCHAR* argv[])
{
//static_cast 最常用的类型转换符
float f = 66.5;
char c =static_cast<char>(f);
cout << c << endl;
cout <<"********************"<<endl;
//const_cast 用于去出const属性,把const类型的指针变为非const类型的指针
const int a = 100;
const int *p = &a;
int *m = const_cast<int *>(p);
*m = 50;
cout << "a = " << a << endl;
cout << "*p= " << *p << endl;
cout << "*m= " << *m << endl;
cout << "******************"<<endl;
//dynamic_cast 该操作符用于运行时检查该转换是否类型安全,但只在多态类型时合法,即该类至少具有一个虚拟方法。
Base *pBase;
Derived derived;
pBase = &derived;
pBase->m();
if(Derived *pDerived = dynamic_cast<Derived *> (pBase))
pDerived->fun();
//reinterpret_castinterpret是解释的意思,reinterpret即为重新解释,此标识符的意思即为数据的二进制形式重新解释,但是不改变其值。
int i;
char *ptr = "hello world!";
i = reinterpret_cast<int>(ptr);
cout << "i = " << endl;
return 0;
}