服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++ 的类型转换详解

C++ 的类型转换详解

2022-02-17 16:36ALL IN C C/C++

本篇文章是对C++ 类型转换的详细介绍,需要的朋友参考下,小编觉得这篇文章写的不错,希望能够给你带来帮助

一、C++ 类型转换

1.静态类型转换

1.语法格式

?
1
static_cast<目标类型> (标识符)

2.转化规则

在一个方向上可以作隐式转换,在另外一个方向上就可以作静态转换。

?
1
2
3
4
int a = 10;
int b = 3;
cout<<static_cast<float>(a)/b<<endl; //float = int int = float
return 0;
?
1
2
int *p; void *q;
p = static_cast<int*>(q);
?
1
char *p = static_cast<char*>(malloc(100));

2.重解释类型转换

1.语法格式

?
1
reinterpret_cast<目标类型> (标识符)

2.转化规则

将数据以二进制存在形式的重新解释,在双方向上都不可以隐式类型转换的,则需要重解释类型转换

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    int x = 0x12345648;
    char *p = reinterpret_cast<char*>(&x);
    //char*p = static_cast<char*>(&x); error
    printf("%x\n",*p);
    int a[5] = {1,2,3,4,5};
    int *q = reinterpret_cast<int*>(a+1);
    printf("%x\n",*q);
    return 0;
}

C++ 的类型转换详解

3.常类型转换

1.语法格式

?
1
const_cast<目标类型> (标识符) //目标类类型只能是指针或引用。

2.语法规则

用来移除对象的常量性使用 const_cast 去除 const 限定的,目的不是为了修改它的内容,使用 const_cast 去除 const 限定,通常是为了函数能够接受这个实际参数。

?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
void func(int & ref) //别人己经写好的程序或类库
{
    cout<<ref<<endl;
}
int main(void)
{
    const int m = 1;
    func(const_cast<int&>(m));
    return 0;
}

脱掉const后的引用或指针可以改吗

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;
int main()
{
    const int x = 200;
    int & a =const_cast<int&>(x); // int &a = x;
    a = 300;
    cout<<a<<x<<endl;
    cout<<&a<<"---"<<&x<<endl;
    int *p =const_cast<int*>(&x); // int *p = &x;
    *p = 400;
    cout<<a<<*p<<endl;
    cout<<p<<"---"<<&x<<endl;
    struct A
    {
        int data;
    };
    const A xx = {1111};
    A &a1 = const_cast< A&>(xx);
    a1.data = 222;
    cout<<a1.data<<xx.data<<endl;
    A *p1 = const_cast<A*>(&xx);
    p1->data = 333;
    cout<<p1->data<<xx.data<<endl;
    return 0;
}

C++ 的类型转换详解

结论:可以改变 const 自定义类的成员变量,但是对于内置数据类型,却表现未定义行为

3.const 常变量(补充)

C++中 const 定义的变量称为常变量。变量的形式,常量的作用,用作常量,常用于取代#define 宏常量

4.动态类型转换

1.语法格式

?
1
dynamic_cast<目标类型> (标识符)

用于多态中的父子类之间的强制转化

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/qq_43414070/article/details/121021741

延伸 · 阅读

精彩推荐