博客
关于我
C++类型转换总结
阅读量:431 次
发布时间:2019-03-06

本文共 1435 字,大约阅读时间需要 4 分钟。

C++风格的类型转换提供了四种类型转换操作符,分别适用于不同的场景。以下是对每种转换的详细分析:

1. const_cast

const_cast 用于去掉类型的 const 或 volatile 属性。例如:

struct SA {    int i;};const SA ra;// ra.i = 10; 直接修改 const 类型,编译错误SA & rb = const_cast
(ra);rb.i = 10; // 可以正常修改

2. static_cast

static_cast 类似于 C 风格的强制转换,无条件转换,适用于基本类型和类之间的转换。例如:

int n = 6;double d = static_cast
(n); // 基本类型转换int* pn = &n;double* d = static_cast
(pn); // 无关类型指针转换,编译错误void* p = static_cast
(pn); // 任意类型转换成 void 类型

3. dynamic_cast

dynamic_cast 用于动态类型转换,需要运行时类型信息,通常用于多态类。例如:

class BaseClass {    public:    int m_iNum;    virtual void foo(){}; // 基类必须有虚函数};class DerivedClass: public BaseClass {    public:    char* m_szName[100];    void bar(){};};BaseClass* pb = new DerivedClass();DerivedClass* pd1 = static_cast
(pb); // 子类 → 父类,静态类型转换,正确但不推荐DerivedClass* pd2 = dynamic_cast
(pb); // 子类 → 父类,动态类型转换,安全BaseClass* pb2 = new BaseClass();DerivedClass* pd21 = static_cast
(pb2); // 父类 → 子类,静态类型转换,危险DerivedClass* pd22 = dynamic_cast
(pb2); // 父类 → 子类,动态类型转换,安全

4. reinterpret_cast

reinterpret_cast 仅重新解释类型,不执行二进制转换,通常用于指针和算术类型。例如:

int doSomething(){return 0;};typedef void (*FuncPtr)();FuncPtr funcPtrArray[10];funcPtrArray[0] = reinterpret_cast
(doSomething); // 不同函数指针类型之间进行转换

总结

  • 使用 const_cast 去掉 const 或 volatile 属性。
  • 对基本类型转换使用 static_cast。
  • 对多态类转换使用 dynamic_cast。
  • 对不同指针类型转换使用 reinterpret_cast。

转载地址:http://mlpuz.baihongyu.com/

你可能感兴趣的文章
poj 1125Stockbroker Grapevine(最短路)
查看>>
poj 1151 (未完成) 扫描线 线段树 离散化
查看>>
POJ 1151 / HDU 1542 Atlantis 线段树求矩形面积并
查看>>
poj 1163 数塔
查看>>
POJ 1177 Picture(线段树:扫描线求轮廓周长)
查看>>
POJ 1182 食物链(并查集拆点)
查看>>
POJ 1185 炮兵阵地 (状态压缩DP)
查看>>
POJ 1195 Mobile phones
查看>>
POJ 1228 Grandpa's Estate (稳定凸包)
查看>>
poj 1236(强连通分量分解模板题)
查看>>
poj 1258 Agri-Net
查看>>
poj 1286 Necklace of Beads
查看>>
POJ 1321 棋盘问题
查看>>
poj 1321(回溯)
查看>>
Qt读取注册表默认值
查看>>
poj 1679 判断MST是不是唯一的 (次小生成树)
查看>>
POJ 1703 Find them, Catch them
查看>>
POJ 1703 Find them, Catch them 并查集
查看>>
POJ 1738 An old Stone Game(石子合并)
查看>>
POJ 1740 A New Stone Game(博弈)题解
查看>>