C++中的新式类型转换

举报
yd_274589494 发表于 2023/07/27 17:37:45 2023/07/27
661 0 0
【摘要】 @TOC 前言本篇文章给大家介绍C++中的几种新式类型转换。 一、static_caststatic_cast用法:1.用于基本类型间的转换 int a = 67; char b = static_cast<char>(a);//true cout << a << endl; cout << b << endl;2.不能用于基本类型指针间的转换 int a = ...

@TOC


前言

本篇文章给大家介绍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);

总结

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

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。