static_cast 运算符的特点

本文介绍了C++中static_cast运算符的功能与用法,并通过一个具体的示例代码展示了如何使用static_cast来进行类型转换,包括从基类到派生类的安全转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     static_cast运算符是标准c++中的强制类型转换运算符。原先的c语言中是存在类型转换的,如int型直接转换为float型,为什么需要引入新的类型转换?目的是为了克服旧式c语言中类型转换的缺陷。旧式的类型转换是很强的一种语法,带来的后果是引入很多不易察觉的错误。static_cast比旧式的类型转换更具体,更安全,类型转换的错误能在编译期间发现。例如,const类型转换为非const类型在编译期间被认为是一个语法错误。

#include<iostream>
using namespace std ;

  class animal {
   
    public:
    void print(void) const{
        
    cout<<"this is a animal"<<endl;} 
};

class fish : public animal{
    public:
    void print(void) const{
    cout <<"this is a fish"<<endl;
}   
};

void test(animal *animalPtr)
{
    fish * fishPtr;
  fishPtr=static_cast<fish *>(animalPtr);
  //可以用static_cast进行基类向派生类的转换
   //  fishPtr= animalPtr;
   //无效的类型转换
     fishPtr->print();
     animalPtr=fishPtr;
     animalPtr->print();
}  ;  

 int main()
 {      
     animal theanimal;
     test(&theanimal);
    
     cin.get();
 }         

 //输出的结果是 
       this is a fish
      this is a animal

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值