c++ 中几个常见的强制类型转换

来源:互联网 发布:爱淘宝买东西返利多少 编辑:程序博客网 时间:2024/05/18 19:44

1) static_cast

在C++语言中static_cast用于数据类型的强制转换,强制将一种数据类型转换为另一种数据类型:结构如下

static_cast <类型说明符> (变量或表达式)如:

int a = 10 ;

int b = 3;

double result  = static_cast <double> (a) / static_cast <double> (b);


2) const_cast

在C语言中,const限定符通常被用来限定变量,用于表示该变量的值不能被修改。而const_cast则正是用于强制去掉这种不能被修改的常数特性,但需要特别注意的是const_cast不是用于去除变量的常量性,而是去除指向常数对象的指针或引用的常量性,其去除常量性的对象必须为指针或引用。但是该参数不能对一般的变量进行转换,只能对指针或者引用进行装换,否则会出现编译错误;

如下:


#include <iostream>
using namespace std;

const int * Search(const int * a,int n,int val);

int main()
{
    int a[10] = {0,1,2,3,4,5,6,7,8,9};
    int val = 5;
    int *p;
    p = const_cast<int *>(Search(a,10,val));
    if (p == NULL)
        cout << "Not found the val in array a" << endl;
    else
        cout << "have found the val in array a and the val = " << *p << endl;
    getchar();
    return 0;
}

const int * Search(const int * a, int n, int val)
{
    int i;
    for (i = 0; i < n; i++)
    {
        if (a[i] == val)
            return &a[i];
    }
    return NULL;
}

3) reinterpret_cast

在C++语言中,reinterpret_cast主要有三种强制转换用途:改变指针或引用的类型、将指针或引用转换为一个足够长度的整形、将整型转换为指针或引用类型。在使用reinterpret_cast强制转换过程仅仅只是比特位的拷贝,因此在使用过程中需要特别谨慎!





0 0
原创粉丝点击