41、类型转换函数

标准数据类型之间会进行隐式的类型安全转换,规则如下:

char->short->int->unsigned int->long->unsigned long->float->double   小转大

#include <iostream>

#include <string>
using namespace std;
int main()
{   
    short s = 'a';                      //  char转化为 short
    unsigned int ui = 1000;    //  int 转化为 unsigned int
    int i = -2000;                     
    double d = i;                     // int 转化为double
    cout << "d = " << d << endl;
    cout << "ui = " << ui << endl;       
    cout << "ui + i = " << ui + i << endl;
    if( (ui + i) > 0 )                    //有符号和无符号的相加,将 i 默认转化为 unsigned int,相当于两个无符号相加
    {
        cout << "Positive" << endl;
    }
    else
    {
        cout << "Negative" << endl;
    }    
    cout << "sizeof(s + 'b') = " << sizeof(s + 'b') << endl;      // 将s和‘b’都转化为 int ,打印出4
    return 0;

}

普通类型与类类型之间能否进行类型转换?类类型之间能否相互转换?

再论构造函数,

构造函数可以定义不同类型的参数。

参数满足下列条件时称为转换构造函数:

有且仅有一个参数,参数是基本类型,或者参数是其他类类型。


 旧式的c方式强制类型转换:  int i;Test t;  i=int(5); t=Test(100);

编译器会尽力尝试让源码通过编译,Teat  t;   t=100;  100这个立即数默认为int类型,怎么可能赋值给t对象呢,编译器会看看有没有转换构造函数,发现Test类中定义了 Test(int i),可以进行转换,默认等价于:t=Test(100);

Test t; t=5;  // t=Test(5); 隐式类型转换

编译器尽力尝试的结果是隐式类型转换

隐式类型转换:会让程序以意想不到的方式进行工作,是工程的bug的重要来源。

工程中通过 explicit 关键字杜绝编译器的转换尝试,转换构造函数被 explicit 修饰时只能进行显示转换,

强制转换方式:

static_cast<ClassName>(value);  //c++中

ClassName(value);     //c语言中

(ClassName)value;     //c语言中,不推荐

#include <iostream>
#include <string>
using namespace std;
class Test
{
    int mValue;
public:
    Test()
    {
        mValue = 0;
    }    
    explicit Test(int i)           // 杜绝隐式转换
    {
        mValue = i;
    }   
    Test operator + (const Test& p)
    {
        Test ret(mValue + p.mValue);        
        return ret;
    }    
    int value()
    {
        return mValue;
    }
};
int main()
{   
    Test t;    
    t = static_cast<Test>(5);             // t = Test(5);    
    Test r ;    
    r = t + static_cast<Test>(10);   // r=t+10;   <---->    r = t + Test(10);   
    cout << r.value() << endl;    
    return 0;

}

static_cast: 基本类型和类类型间转换

转换构造函数只有一个参数,它的参数类型是其它类型,在类型转换时被调用,隐式转换时bug的重要来源,explcit用于杜绝隐式类型转换。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值