Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++类型强制转换

作者:热血震荡   发布日期:2025-11-07   浏览:63

#include <iostream>
using namespace std;

int main() {
    // 静态类型转换 (static_cast)
    double d = 10.5;
    int i = static_cast<int>(d);  // 将double转换为int,结果为10
    cout << "static_cast: " << i << endl;

    // 动态类型转换 (dynamic_cast),主要用于类层次结构中的指针或引用的向下转型
    class Base {};
    class Derived : public Base {};

    Base* basePtr = new Derived();
    Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);  // 安全地将Base*转换为Derived*
    if (derivedPtr) {
        cout << "dynamic_cast: successful cast" << endl;
    } else {
        cout << "dynamic_cast: failed cast" << endl;
    }

    // 常量类型转换 (const_cast)
    const int constValue = 20;
    int* nonConstPtr = const_cast<int*>(&constValue);  // 移除const属性
    *nonConstPtr = 30;  // 修改值(不推荐,因为constValue仍然是const)
    cout << "const_cast: " << *nonConstPtr << endl;

    // 重解释类型转换 (reinterpret_cast),用于低级别的类型转换
    int intValue = 42;
    void* voidPtr = reinterpret_cast<void*>(intValue);  // 将int重新解释为void*
    cout << "reinterpret_cast: " << voidPtr << endl;

    return 0;
}

解释说明:

  1. 静态类型转换 (static_cast)

    • 用于基本类型的转换,如从 double 转换为 int
    • 是最常用的类型转换方式之一,编译时检查。
  2. 动态类型转换 (dynamic_cast)

    • 主要用于类层次结构中的指针或引用的向下转型。
    • 只能在继承关系中使用,并且需要运行时支持(RTTI)。
    • 如果转换失败,返回 nullptr 或抛出异常(对于引用类型)。
  3. 常量类型转换 (const_cast)

    • 用于移除变量的 constvolatile 属性。
    • 使用时需谨慎,因为修改原本是 const 的对象会导致未定义行为。
  4. 重解释类型转换 (reinterpret_cast)

    • 用于低级别的类型转换,通常用于指针之间的转换。
    • 不保证语义上的正确性,仅在某些特定场景下使用。

上一篇:c++rand函数

下一篇:c++输出字符串

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

c++ random函数用法

队列c++

c++freopen怎么用

进制转换c++代码

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站