C++类型转换

一、C语言中的类型转换

int main()
{
  int i=1;
  double d=i;         //隐式类型转换
  printf("%d,%.2f\n",i,d);
  
  int * p=&i;
  int ar=(int)p;             //显示的强制类型转换
  printf("%x,%d\n",p,address);
}

缺陷:转换的可视性较差,难以发现错误的转换

二、C++强制类型转换
C++引入四种命名的强制类型转换操作符:
static_cast,reinterpret_cast,const_cast,dynamic_cast
1.static_cast
用于非多态类型的转换(静态转换),编译器隐式执行的任何类型转换都可以用static_cast,但不能用于不相关的类型转换

int main()
{
  int i;
  double d=2.0;
  i=static_cast<int>(d);
  cout<<i<<endl;
  return 0;
}

2.reinterpret_cast
通常为操作数的位模式提供较低层次的重新解释,用于将一种类型转换为另一种不同的类型

typedef void (*Func)();
int DoSomething(int i)
{
    cout<<"DoSomething"<<endl;
    return 0;
}
void Test()
{
    //reinterpret_cast让编译器以Func的定义方式看待DoSomething函数
    //但是转换函数指针的代码是不可移植的,所以不建议这样使用
    Fun f=reinterpret_cast<Func>(DoSomething);
    f();
}

3.const_cast
最常用于删除变量的const属性,便于赋值

void Test()
{
  const int a=2;
  int* p=const_cast<int*>(&a);

  *p=4;
  cout<<a<<endl;
 }

4.dynamic_cast
用于将一个父类对象的指针转换为子类对象的指针或引用(动态转换)
向上转型:子类对象指针->父类对象指针/引用(不需要转换,赋值兼容规则)
向下转型:父类对象指针->子类指针/引用(用dynamic_cast转型是安全的)

  • dynamic_cast只能用于含有虚函数的类
  • dynamic_cast会先检查是否能够转换成功,能成功则转换,不能则返回0
class Person
{
   public: 
      virtual void f() {}
};
class Student:public Person
{
};
void fun(Person* p)
{
   Student* s1=static_cast<Student*>(p);
   Student* s2=dynamic_cast<Student*>(p);      //dynamic_cast会先检查能否转换成功,能成功则转换,否则返回0
  
  cout<<"s1:"<<s1<<endl;
  cout<<"s2:"<<s2<<endl;
}
int main()
{
  Person p;
  Student s;
  fun(&p);
  fun(&s);
  return 0;
}
      

5.explicit
explicit关键字阻止经过转换构造函数进行的隐式转换的发生

class A
{
  public:
     explicit A(int a)
     {
        cout<<"A(int a)"<<endl;
     }
     A(const A& a)
     {
        cout<<"A(const A& a)<<endl;
      }
   private:
      int _a;
}
int main()
{
   A a1(1);
   A a2=1;        //隐式类型转换  A tmp(1) ; A a2(tmp);
}
  

三、RTTI
运行时类型识别
C++通过下面方式支持RTTI:

  • typeid运算符
  • dynamic_cast运算符
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值