C++强制类型转换操作符之static_cast

C++强制类型转换操作符之static_cast

static_cast在功能上基本与C风格的类型转换一样强大,含义也一样,它也有功能上的限制。例如,不能用static_cast像用C风格的类型转换一样把int类型转换为指针类型;另外,static_cast不能从表达式中去除const属性或volatile属性。

  • static_cast可以完成C++编译器隐式执行的类型转换。编译器会对有些隐式类型转换发出警告,这时可以使用static_cast来消除警告
class Book{
public:
    Book(int number, string name=""):number(number),name(name){}
    int number;
    string name;
};
int main()
{
    Book book = static_cast<Book>(1002);
    cout << book.number << endl;      //输出:1002
    return 0;
}
    double i = 2.3;
    int j = i;    //warning
    j = static_cast<int>(i);    //no warning
  • static_cast支持void*指针与类型指针之间转换。
class Book{
public:
   Book(int number, string name):number(number),name(name){}
   int number;
   string name;
};

class Animal{
public:
   Animal(int age, int height, string name):age(age),height(height),name(name){}
   int age;
   int height;
   string name;
};
int main()
{
   Book *book = new Book(1001, "C++ primer");
   void * object = static_cast<void *>(book);
   Animal *animal = static_cast<Animal*>(object);
   cout << animal->name << endl;                       //运行时错误
   delete book;
   return 0;
}
  • static_cast不像C风格的类型转换一样把int类型转换为指针。
    int i = 0;
    void *p = (void *)i;   //fine
    void *p = static_cast<void*>(i);   //error
  • static_cast可以实现在基类指针与派生类指针,和基类引用与派生类引用之间的强制转换。static_cast不做运行时的检查,不如dynamic_cast安全,但比dynamic_cast效率高。
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值