C++类型强转

C++类型转换详解

C++(四)类型强转

新类型的强制转换可以提供更好的控制强制转换过程,允许控制各种不同种类的强
制转换。C++提供了四种转化 static_cast,reinterpret_cast,dynamic_cast
和 const_cast 以满足不同需求,C++风格的强制转换好处是,它们能更清晰的表明
它们要干什么。

C 语言转换风格,在 C++中依然适用。

static_cast

语法格式 static_cast(expression)
适用场景 static_cast 是 C++ 中的一种类型转换操作符,用于在相关类型之间进行显式转换。它提供了比 C 风格的类型转换更严格的类型检查,并且在许多情况下比 reinterpret_cast 更安全。
1. 基本数据类型之间的转换
static_cast 可以用于基本数据类型之间的转换,例如将 int 转换为 float,或者将 double 转换为 int:
        
        int i = 42;
        float f = static_cast<float>(i); // 将 int 转换为 float
        
        double d = 3.14;
        int j = static_cast<int>(d); // 将 double 转换为 int
        CopyInsert
2. 指针类型之间的转换
在指针类型之间进行转换时,static_cast 可以用于在相关类型之间进行转换,例如在基类指针和派生类指针之间进行转换:
        
        class Base {
        public:
            virtual void print() {
                std::cout << "Base" << std::endl;
            }
        };
        
        class Derived : public Base {
        public:
            void print() override {
                std::cout << "Derived" << std::endl;
            }
        };
        
        Base* basePtr = new Derived();
        Derived* derivedPtr = static_cast<Derived*>(basePtr); // 将基类指针转换为派生类指针
        derivedPtr->print(); // 输出 "Derived"
        CopyInsert
3. 枚举类型和整数类型之间的转换
static_cast 可以用于枚举类型和整数类型之间的转换:
        
        enum Color { RED, GREEN, BLUE };
        
        Color c = RED;
        int i = static_cast<int>(c); // 将枚举类型转换为整数类型
        
        int j = 1;
        Color c2 = static_cast<Color>(j); // 将整数类型转换为枚举类型
        CopyInsert
4. 空指针类型的转换
static_cast 可以用于将 void* 指针转换为具体类型的指针:
        
        void* voidPtr = malloc(sizeof(int));
        int* intPtr = static_cast<int*>(voidPtr); // 将 void* 指针转换为 int* 指针
        *intPtr = 42;
        CopyInsert
5. 移除 const 限定符
虽然 static_cast 不能直接移除 const 限定符,但可以通过 const_cast 移除 const 后,再使用 static_cast 进行转换:
        
        const int* constPtr = new int(42);
        int* nonConstPtr = const_cast<int*>(constPtr); // 移除 const 限定符
        int value = *nonC
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可能只会写BUG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值