C++深度解析 类型转换函数(上)--- 转换构造函数(40)
类型转换
标准数据类型之间会进行隐式的类型安全转换
示例分析:(隐式转换)
#include <iostream>
#include <string>
using namespace std;
int main()
{
//小类型初始化大类型
//char -->> short
short s = 'a';
//int -->> unsigned int
unsigned int ui = 1000;
int i = -2000;
//int -->> double
double d = i;
cout << "d = " << d << endl;
cout << "ui = " << ui << endl;
cout << "ui + i = " << ui + i << endl;
//隐式规则,将变量i的类型int转换为unsigned int
if ((ui + i) > 0)
{
//正数
cout << "Positive" << endl;
}
else
{
//负数
cout << "Negative" << endl;
}
//转换为int(4个字节)
cout << "sizeof(s + 'b') = " << sizeof(s + 'b') << endl;
return 0;
}
结果如下:
转换构造函数
- 有且仅有一个参数
- 参数是基本类型
- 参数是其他类类型
编译器的行为
编译器会尽力尝试让源码通过编译
Test t;
t = 100;
100这个立即数默认为int类型,怎么可能赋值给t对象呢!现在就报错吗?不急,我看看有没有转换构造函数!OK,发现Test类中定义了Test(int i),可以进行转换,默认等价于:t = Test(100);
编译器尽力尝试的结果是隐式类型转换
隐式类型转换:
会让程序以意想不到的方式进行工作;
是工程中bug的重要来源。
explicit
工程中通过explicit关键字杜绝编译器的转换尝试
转换构造函数被explicit修饰时只能进行显示转换
转换方式:
- static_cast<ClassName>(value);
- ClassName(value);
- (ClassName)value; //不推荐
示例程序:(类类型之间进行类型转换)
#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 = Test(5);
t = static_cast<Test>(5); // t = 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;
}
结果如下:
小结
转换构造函数只有一个参数
转换构造函数的参数类型是其他类型
转换构造函数在类型转换时被调用
隐式类型转换时工程中bug的重要来源
explicit关键字用于杜绝隐式类型转换