C++11Static_cast

#include<iostream>
#include<string>
using namespace std;
//static_cast本质上就是明确隐式转换的,明确的作用
//基类与派生类之间的转换
class Cfather
{
public:
    Cfather() {
        m_ntest = 3;
    }
    virtual void foo() {
        cout << "cfather::void foo()" << endl;
    }
    int m_ntest;
};
class Cson :public Cfather
{
    virtual void foo() {
        cout << "cson::void foo()" << endl;
    }
};


class Cint
{
public:
    operator int() {
        return m_mint;
    }
    int m_mint;
};
int main()
{
    int n = 5;
    float f = 10.0f;
    double dbl = 10.0f;
    //本质上发生了隐式转换,但代码上体现的不明确
    f = n;
    //static_cast,将隐式转换明确
    f = static_cast<float>(n);

    //低风险的转换:都是允许的
    //整形与浮点型,最多丢失精度(扩展精度),
    n = static_cast<int>(dbl);
    //字符与整形,也是精度问题
    char ch = 'a';
    n = static_cast<int>(ch);
    //指针转换,void *指针的转换
    void* p = nullptr;
    int* p1 = static_cast<int*>(p);
    //转换运算符的方式
    Cint obj;  
    int k = static_cast<int>(obj);//如果类中没有提供转换运算符,
                                //那么编译不过,它无法将一个对象换换位int
    cout << n << " " << f << endl;

    //高风险的转换:
    int kk;
    char* p;
    //整型与指针类型转换。隐式转换操作不了。
    /*p = kk;*/
    /*char* k = static_cast<char*>(kk);*///高风险的转换无论是隐式还是static_cast都不能成功
    int* pk;
    /*char* k = static_cast<char*>(pk);两种方法也是都不能转换*/
    


    //基类与派生类之间的转换
    Cfather* father = nullptr;
    Cson* son = nullptr;
    //父类转子类(不安全)
    /*son = father;编译不能通过,*/
    son = static_cast<Cson *>(father);//可以转换,不安全,没有提供运行时的检测。
    //子类转父类(安全)
    father = son;
    father = static_cast<Cfather*>(son);//两个都可以转换
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值