本文内容来自于对狄泰学院 唐佐林老师 C++深度解析 课程的学习总结
再论类型转换
标准数据类型之间会进行 隐式的类型安全转换
转换规则如下:
隐式规则为小类型往大的类型转
实验编程
我们来写一个程序来测试基本类型的转换
#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;
cout << "sizeof(s) = " << sizeof(s) << endl;
cout << "sizeof('b') = " << sizeof('b') << endl;
cout << "sizeof(s + 'b') = " << sizeof(s+'b') << endl;
return 0;
}
运行结果
实验结果:当 int 类型和 unsigned int 类型一起运算时,int 类型被隐式转换成了 unsigned int 类型。char 类型和 short 类型一起运算时,char 类型被转换成了 short 类型。
再论构造函数
- 构造函数可以定义 不同类型的参数
- 参数满足下列条件时称为 转换构造函数
1.有且仅有一个参数
2.参数是基本类型
3.参数是其它类类型
旧式的 C 方式强制类型转换
编译器的行为
- 编译器会尽力尝试让源码通过编译
- 编译器 尽力尝试 的结果是 隐式类型转换
- 隐式类型转换
会让程序以 意想不到 的方式进行工作
是工程中 bug 的重要来源 - 工程中通过 explicit 关键字 杜绝编译器的转换尝试
- 转换构造函数被 explicit 修饰时只能进行显示转换
转换方式
示例代码
#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 + Test(10);
cout << r.value() << endl;
return 0;
}
运行结果
小结
转换构造函数 只有一个参数
转换构造函数的 参数类型是其它类型
转换构造函数在 类型转换时被调用
隐式类型转换 是工程中 bug 的重要来源
explicit 关键字用于 杜绝 隐式类型转换