博客
关于我
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/

你可能感兴趣的文章
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>