首页 > 编程语言 > 详细

C++四种强制类型转换

时间:2015-12-16 09:38:50      阅读:268      评论:0      收藏:0      [点我收藏+]

    大家都知道在C语言里强制类型转换的方法非常简单,只要在要转换的变量前用括号确定要转换的类型即可,如要将一个double型的变量强制转换为int类型,代码如下:
   double x = 3.14;
   int y = (int)x;
另外,还可有更高级的转换,如把int *类型的变量转换为int ,代码如下:
   int x = 20;
   int *p = &x;
   int y = (int)p;

在C++语言里为了让强制类型转换更明显,更安全,所以把不同情况下的强制类型转换分为四种,分别为:
static_cast       静态类型转换,属于最安全的强制类型转换。
const_cast             在可变与不可变类型之间转换
dynamic_cast       在多态的情况下,父子类之间的转换
reinterpret_cast       所有类型间的转换,最不安全的转换

为了更好的说明问题,下面举几个使用方面的具体例子,代码如下:

static_cast
--------------------------------------------------------------------

int main()
{
   int x = 0;
   double y = 3.14;
   x = static_cast<int>(y);

   system("pause");
   return 0;
}

--------------------------------------------------------------------

const_cast
--------------------------------------------------------------------

int main()
{
   int x = 20;
   int const *p = &x;
   int *q = const_cast<int *>(p);

   system("pause");
   return 0;
}

--------------------------------------------------------------------

dynamic_cast
--------------------------------------------------------------------

#include <iostream>
using std::cout;
using std::endl;

//X类是父类
class X
{
public:
   void test()
   {
      cout << "Xtest" << endl;
   }

   //虚函数
   virtual void foo()
   {
      cout << "XFoo" << endl;
   }
};


//Y类是子类,继承了X类
class Y : public X
{
public :
   void TTT()
   {
      cout << "YTTT" << endl;
   }

   //重写的虚函数
   virtual void foo()
   {
      cout << "YFoo" << endl;
   }
};

//
int main()
{
   X *p = new Y;
   dynamic_cast<Y *>(p)->TTT();
   
   system("pause");
   return 0;
}

--------------------------------------------------------------------

reinterpret_cast
--------------------------------------------------------------------

int main()
{
   int x = 20;
   int *p = &x;
   int z = reinterpret_cast<int>(p);

   system("pause");
   return 0;
}

--------------------------------------------------------------------

本文出自 “8403723” 博客,请务必保留此出处http://8413723.blog.51cto.com/8403723/1723411

C++四种强制类型转换

原文:http://8413723.blog.51cto.com/8403723/1723411

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!