头图

标准数据类型之间会进行因式类型安全转换

转换规则如下:

Slide2.PNG

#include <iostream>
#include <string>

using namespace std;

int main()
{   
    short s = 'a';
    unsigned int ui = 1000;
    int i = -2000;
    double d = i;
    
    cout << "d = " << d << endl;
    cout << "ui = " << ui << endl;
    cout << "ui + i = " << ui + i << endl;
    
    if( (ui + i) > 0 )
    {
        cout << "Positive" << endl;
    }
    else
    {
        cout << "Negative" << endl;
    }
    
    cout << "sizeof(s + 'b') = " << sizeof(s + 'b') << endl;
    
    return 0;
}

再论构造函数

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

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

有且仅有一个参数

参数是基本类型

参数是其他类类型

Slide9.PNG

编译器的行为

工程中通过explicit关键字度杜绝编译器的转换尝试

转换构造函数被explicit修饰时智能进行显示转换

小结:

转换构造函数只有一个参数

转换构造函数的参数类型是其他类型

转换构造函数在类型转换时被调用

隐式类型转换是工程中的bug重要来源

explicit关键字用于杜绝隐式类型转换


YingLi
6 声望4 粉丝

From zero to hero.