一、基本内置类型转换

1. 隐式转换(自动转换)

int a = 10;
double b = a;  // int → double
float f = b;   // double → float

2. C风格显式转换

int x = 10;
double y = (double)x;  // C风格转换
char c = char(x);      // 函数式风格

二、C++风格转换操作符

1. static_cast - 最常用的类型转换

// 基础类型转换
int i = 100;
float f = static_cast<float>(i);

// 指针/引用转换(相关类型)
Base* base = new Derived();
Derived* derived = static_cast<Derived*>(base);  // 下行转换(不安全)

// 枚举与整数转换
enum Color { RED, GREEN, BLUE };
int color_val = static_cast<int>(RED);

// void* 转换
int* p = new int(10);
void* vp = static_cast<void*>(p);
int* p2 = static_cast<int*>(vp);

2. dynamic_cast - 运行时类型检查(多态类型)

class Base { virtual void foo() {} };
class Derived : public Base {};

Base* base = new Derived();
Derived* derived = dynamic_cast<Derived*>(base);  // 安全的下行转换

if (derived) {  // 检查是否转换成功
    // 转换成功
}

3. const_cast - 移除或添加 const/volatile

const int ci = 10;
int* modifiable = const_cast<int*>(&ci);  // 移除const

// 添加const
int x = 5;
const int* pcx = const_cast<const int*>(&x);

// volatile 转换
volatile int vi = 20;
int* normal = const_cast<int*>(&vi);

4. reinterpret_cast - 重新解释底层位模式

// 指针类型转换
int* ip = new int(65);
char* cp = reinterpret_cast<char*>(ip);  // 将int*重新解释为char*

// 指针与整数转换
intptr_t addr = reinterpret_cast<intptr_t>(ip);  // 指针转整数
int* ip2 = reinterpret_cast<int*>(addr);         // 整数转指针

三、标准库转换函数

1. 数值 ↔ 字符串转换(C++11起)

// 数字转字符串
#include <string>
std::string str;
str = std::to_string(100);      // int → string
str = std::to_string(3.14);     // double → string
str = std::to_string(true);     // bool → "1" or "0"

// 字符串转数字
int i = std::stoi("100");        // string → int
double d = std::stod("3.14");    // string → double
long l = std::stol("1000000");   // string → long
float f = std::stof("3.14");     // string → float

// 进制转换
int hex = std::stoi("FF", nullptr, 16);  // 十六进制
int bin = std::stoi("1010", nullptr, 2); // 二进制

2. std::bitset - 二进制转换

#include <bitset>
std::bitset<8> bits(42);         // 整数转二进制
int num = bits.to_ulong();       // 二进制转整数
std::string str = bits.to_string(); // 二进制字符串

3. std::any - 任意类型转换(C++17)

#include <any>
std::any a = 42;
int i = std::any_cast<int>(a);

std::any b = std::string("hello");
std::string s = std::any_cast<std::string>(b);

4. std::variant - 类型安全联合(C++17)

#include <variant>
std::variant<int, double, std::string> v = 42;
int i = std::get<int>(v);  // 获取int值

v = 3.14;
double d = std::get<double>(v);  // 获取double值

5. 字符编码转换

#include <codecvt>
#include <locale>
#include <string>

// wstring ↔ string 转换
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
std::wstring wide = L"宽字符";
std::string narrow = converter.to_bytes(wide);  // wide → narrow
std::wstring wide2 = converter.from_bytes(narrow);  // narrow → wide

四、用户自定义类型转换

1. 转换构造函数

class MyClass {
public:
    MyClass(int x) : value(x) {}  // 转换构造函数:int → MyClass
    int value;
};

MyClass obj = 10;  // 隐式转换:int → MyClass

2. 转换运算符

class MyClass {
public:
    operator int() const {  // 转换运算符:MyClass → int
        return value;
    }
    operator std::string() const {  // MyClass → string
        return std::to_string(value);
    }
private:
    int value = 42;
};

MyClass obj;
int i = obj;            // 隐式调用 operator int()
std::string s = obj;    // 隐式调用 operator string()

3. 显式转换运算符(C++11)

class MyClass {
public:
    explicit operator bool() const {  // 显式转换
        return value != 0;
    }
private:
    int value = 10;
};

MyClass obj;
if (static_cast<bool>(obj)) {  // 必须显式转换
    // ...
}

五、智能指针转换

#include <memory>

class Base { virtual ~Base() = default; };
class Derived : public Base {};

// 智能指针的 dynamic_cast
std::shared_ptr<Base> base = std::make_shared<Derived>();
std::shared_ptr<Derived> derived = 
    std::dynamic_pointer_cast<Derived>(base);

// static_pointer_cast, const_pointer_cast
std::shared_ptr<const int> const_ptr = 
    std::make_shared<const int>(10);
std::shared_ptr<int> mutable_ptr = 
    std::const_pointer_cast<int>(const_ptr);

六、类型识别与转换

1. typeid 运算符

#include <typeinfo>
int i;
const std::type_info& ti = typeid(i);
if (ti == typeid(int)) {
    // 类型匹配
}

2. 类型特征(Type Traits)

#include <type_traits>

// 类型转换特征
int i = 10;
auto f = static_cast<std::conditional_t<
    std::is_same<decltype(i), int>::value, 
    float, 
    double>>(i);

// 移除/添加修饰符
std::remove_const<const int>::type          // int
std::add_const<int>::type                   // const int
std::remove_pointer<int*>::type             // int
std::add_pointer<int>::type                 // int*

七、最佳实践建议

  1. 优先使用 C++ 风格转换(static_cast、dynamic_cast 等)

  2. 避免使用 C 风格转换,它过于危险

  3. 使用 explicit 关键字防止隐式转换产生意外结果

  4. 考虑使用类型安全的转换(如 variant、any)

  5. 在性能关键代码中注意转换开销

八、实用转换模板函数

// 安全的数值转换
template<typename To, typename From>
To safe_cast(From value) {
    // 添加边界检查等安全机制
    return static_cast<To>(value);
}

// 带范围检查的转换
template<typename To, typename From>
bool try_cast(From value, To& result) {
    // 实现类型和范围检查
    if (/* 检查通过 */) {
        result = static_cast<To>(value);
        return true;
    }
    return false;
}

这些转换机制覆盖了 C++ 中大部分数据类型转换的场景。根据具体需求选择合适的转换方式,特别是在涉及指针和继承层次结构时要注意安全性。

别忘了点赞收藏关注!!!

更多推荐