标准数据类型之间会进行隐式的类型转化
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;
构造函数可以定义不同类型的参数
构造函数满足下列条件时称为:转化构造函数(加上explicit表明系统不能自己调用,只能用户自我调用)
1,有且只有一个参数
2,参数是基本类型
3,参数是其他类类型
编译器遇到:Test t; t=5; 时,自己会看类中是否定义转化构造函数---------->有,便等价于 t=Test(5);
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; }
类类型转化为基本数据类型
类型转换函数:
1.与转换构造函数具有同等的地位;
2.使得编译器有能力将对象转化为其他类型
3.编译器能够隐式的使用类型装换函数
#include <iostream> #include <string> using namespace std; 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; }