C++中的新式类型转换

简介: C++中的新式类型转换

前言

本篇文章给大家介绍C++中的几种新式类型转换。

一、static_cast

static_cast用法:

1.用于基本类型间的转换

    int a = 67;
    char b = static_cast<char>(a);//true
    cout << a << endl;
    cout << b << endl;

2.不能用于基本类型指针间的转换

    int a = 67;
    char b = static_cast<char>(a);//true
    cout << a << endl;
    cout << b << endl;
    int* p = &a;
    char* p1 = static_cast<char*>(p);//err

3.用于有继承关系对象之间的转换和类指针之间的转换

#include <iostream>
#include <string>
using namespace std;
class Test
{
public:
    Test()
    {
        cout << "Test()" << endl;
    }
    ~Test()
    {
        cout << "~Test()" << endl;
    }
    void print()
    {
        cout << "this is Test()" << endl;
    }
};
class Test1 :public Test
{
public:
    Test1()
    {
        cout << "Test1()" << endl;
    }
    ~Test1()
    {
        cout << "~Test1()" << endl;
    }
    void printf_string()
    {
        cout << "string" << endl;
    }
};
int main()
{
    Test1 t1;
    Test t2 = static_cast<Test>(t1);
    return 0;
}

二、const_cast

const_cast可以清除变量的只读熟悉。

注意:强制转换的目标类型必须是指针或者引用。

此时a不能赋值为其他的数值,因为a是一个只读变量

    const int& a = 10;
    a = 20;//err

使用const_cast清除a的只读属性

const_cast<int &>(a) = 20;//true

三、reinterpret_cast

用于指针类型间的强制类型转换

char a = 10;
char* p = &a;
int* p1 = reinterpret_cast<int*>(p);

用于整数和指针的强制类型转换

int a = 0x220000;
int* p = reinterpret_cast<int*>(a);

四、dynamic_cast

用于有继承关系的类指针间的转换

需要有虚函数的支持

class Test
{
public:
    Test()
    {
        cout << "Test()" << endl;
    }
    virtual void print()
    {
        cout << "hello" << endl;
    }
    ~Test()
    {
        cout << "~Test()" << endl;
    }
};
class Test1 : public Test
{
public:
    Test1()
    {
        cout << "Test1()" << endl;
    }
    void print()
    {
        cout << "hello world" << endl;
    }
    ~Test1()
    {
        cout << "~Test1()" << endl;
    }
};
Test1 t2;
Test1 *t = &t2;
Test *t1 = dynamic_cast<Test1*>(t);

总结

这四个强制类型转换是经常使用的,希望大家掌握。

相关文章
|
5月前
|
安全 编译器 程序员
【C++】C++的类型转换
【C++】C++的类型转换
|
5月前
|
设计模式 安全 算法
【C/C++ 类型转换 】深入理解C++向上转型:从基础到应用
【C/C++ 类型转换 】深入理解C++向上转型:从基础到应用
195 0
|
17天前
|
编译器 C语言 C++
C++入门4——类与对象3-1(构造函数的类型转换和友元详解)
C++入门4——类与对象3-1(构造函数的类型转换和友元详解)
15 1
|
19天前
|
存储 编译器 数据安全/隐私保护
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解2
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解
24 3
|
19天前
|
编译器 C++
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解1
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解
40 3
|
5月前
|
存储 安全 编译器
C++:现代类型转换
C++:现代类型转换
45 5
|
17天前
|
C++
C++入门4——类与对象3-2(构造函数的类型转换和友元详解)
C++入门4——类与对象3-2(构造函数的类型转换和友元详解)
17 0
|
3月前
|
存储 安全 编译器
【C++11】类型转换
【C++11】类型转换
18 0
|
3月前
|
安全 程序员 编译器
C++一分钟之-C++中的类型转换
【7月更文挑战第8天】C++中的类型转换涉及隐式和显式操作,隐式转换如从`int`到`double`是自动的,但可能导致数据丢失。显式转换包括`static_cast`, `dynamic_cast`, `const_cast`, `reinterpret_cast`,以及转换构造函数。要避免数据丢失、类型不匹配和运行时错误,需谨慎使用显式转换并检查结果。过度使用`reinterpret_cast`应避免。理解这些转换有助于编写更安全的代码。
31 0
|
5月前
|
安全 程序员 C语言
从C语言到C++_37(特殊类设计和C++类型转换)单例模式(下)
从C语言到C++_37(特殊类设计和C++类型转换)单例模式
49 5