您的位置:首页 > 编程语言 > C语言/C++

C++中四种类型转换方式

2014-05-25 21:09 357 查看
(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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: