static_cast

static_cast

基本等价于隐式转换的一种类型转换运算符,以前是编译器自动隐式转换,static_cast可使用于需要明确隐式转换的地方。c++中用static_cast用来表示明确的转换。

#include <iostream>
int main()
{
    int n = -1;
    char ch = 'a';
    double dle = 0.1;

    dle = n;  //c语言中的隐式转换

    dle = static_cast<double>(n);
    n = static_cast<int>(ch);

    std::cout << dle << std::endl; //-1
    std::cout << n << std::endl;  //97
    return 0;
}

可以用于低风险的转换。
  • 整型和浮点型

  • 字符与整形

  • 转换运算符

  • *空指针转换为任何目标类型的指针*

不可以用与风险较高的转换
  • 不同类型的指针之间互相转换
  • 整型和指针之间的互相转换
  • 不同类型的引用之间的转换
#include <iostream>
#include <string>

class CInt{
public:
    operator int() {
        return m_nInt;
    }

    int m_nInt;
};

int main() {
    int n = 5;
    double dbl = n;
    char ch = 'a';

    //整型与浮点型
    dbl = static_cast<double>(n);

    //整型与字符型
    ch = static_cast<char>(n);

    //转换运算符
    CInt nObj;
    int k = static_cast<int>(nObj);
}
static_cast用于基类与派生类的转换过程中,但是没有运行时类型检查
#include "stdafx.h"
#include <iostream>
#include <string>

class CFather
{
public:
    CFather() {
        m_nTest = 3;
    }

    virtual void foo() {
        std::cout << "CFather()::void foo()" << std::endl;
    }

    int m_nTest;
};

class CSon : public CFather
{
    virtual void foo() {
        std::cout << "CSon::void foo()" << std::endl;
    }
};


/*
  子类转换成父类:可以。  
  父类转换成子类:不可以。
*/
int main() {
    CFather* pFather = nullptr;
    CSon* pSon = nullptr;

    //pFather = pSon;
    //pFather = static_cast<CFather*>(pSon);

    //pSon = pFather;
    pSon = static_cast<CSon*>(pFather); //是不安全的
   
}
  • 12
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值