标准数据类型之间会进行隐式的类型安全转换
转换规则如下:
下面来看一个有趣的隐式类型转换:
#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; }
输出结果如下:
ui 为 unsigned int 类型,i 为 int 类型,将两者进行相加编译器会进行隐式的类型转换,全部变成unsigned int 类型,所以最后的运行结果是正数。
s 和 'b 编译器都被编译器转换成 int 类型,因为 int 类型的运算是最高效的。
普通类型与类类型之间能否进行类型转换?类类型之间能否进行类型转换?
构造函数可以定义不同类型的参数
参数满足下列条件时称为转换构造函数
旧式的 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; }
输出结果如下:
类类型是否能够类型转换到普通类型?
C++ 类中可以定义类型转换函数
类型转换函数用于将类对象转换为其它类型
语法规则:
下面来看一个类型转换函数:
#include <iostream> #include <string> using namespace std; class Test { int mValue; public: Test(int i = 0) { mValue = i; } int value() { return mValue; } operator int () { return mValue; } }; int main() { Test t(100); int i = t; cout << "t.value() = " << t.value() << endl; cout << "i = " << i << endl; return 0; }
int i = t; 等价于int i = t.operator int ();
类型转换函数
编译器会尽力尝试让源码通过编译
下面看类类型之间的转换:
#include <iostream> #include <string> using namespace std; class Test; class Value { public: Value() { } explicit Value(Test& t) { } }; class Test { int mValue; public: Test(int i = 0) { mValue = i; } int value() { return mValue; } Value toValue() { Value ret; cout << "operator Value()" << endl; return ret; } }; int main() { Test t(100); Value v = t.toValue(); return 0; }
输出结果如下:
注意类型转换函数可能与转换构造函数冲突,所以 explicit Value(Test& t) { } 加了一个 explicit,如果不加,编译器可能会报错。