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

c++强制类型转换

作者:妳明白莪還在等待嗎?   发布日期:2026-03-21   浏览:108

// C++ 强制类型转换示例

#include <iostream>
using namespace std;

int main() {
    // 1. 使用 static_cast 进行基本类型之间的转换
    double d = 123.456;
    int i = static_cast<int>(d);  // 将 double 转换为 int,结果是 123
    cout << "static_cast: " << i << endl;

    // 2. 使用 dynamic_cast 进行类层次结构中的指针或引用转换
    class Base {
    public:
        virtual ~Base() {}
    };

    class Derived : public Base {
    public:
        void derivedFunction() {
            cout << "Derived function called" << endl;
        }
    };

    Base* basePtr = new Derived();
    Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
    if (derivedPtr) {
        derivedPtr->derivedFunction();  // 成功转换后调用派生类的函数
    } else {
        cout << "dynamic_cast failed" << endl;
    }

    delete basePtr;

    // 3. 使用 reinterpret_cast 进行低级类型的重新解释
    int num = 42;
    void* voidPtr = reinterpret_cast<void*>(num);  // 将 int 重新解释为 void*
    cout << "reinterpret_cast: " << voidPtr << endl;

    // 4. 使用 const_cast 去除常量性
    const int constNum = 100;
    int* nonConstPtr = const_cast<int*>(&constNum);  // 去除 const 属性
    *nonConstPtr = 200;  // 修改值(注意:这在某些情况下是不安全的)
    cout << "After modifying via const_cast: " << constNum << endl;

    return 0;
}

解释说明:

  1. static_cast:用于基本类型之间的转换,如 doubleint。它不会进行运行时检查,适用于已知安全的转换。

  2. dynamic_cast:用于类层次结构中的指针或引用转换,特别是当需要从基类指针转换为派生类指针时。它会在运行时进行类型检查,如果转换失败会返回 nullptr(对于指针)或抛出异常(对于引用)。

  3. reinterpret_cast:用于低级类型的重新解释,例如将一个整数重新解释为指针。它不会进行任何类型检查,通常用于底层编程或硬件相关的操作。

  4. const_cast:用于去除变量的 constvolatile 属性。虽然它可以修改常量的值,但在某些情况下这样做是不安全的,可能会导致未定义行为。

上一篇:c++sort

下一篇:c++ typedef

大家都在看

c++闭包

c++向上取整的代码

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

c++ 注释

c++如何判断素数

c++ functional

c++框架代码

c++格式化字符串

c++ orm框架

c++ string类

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

Laravel 中文站