#include<iostream>#include<string>usingnamespace std;intmain(){short s ='a';unsignedint ui =1000;int i =-2000;double d = i;
cout <<"d = "<< d << endl;
cout <<"ui = "<< ui << endl;
cout <<"ui + i = "<< ui + i << endl;//i ==> uiif((ui + i)>0){
cout <<"Positive"<< endl;}else{
cout <<"Negative"<< endl;}
cout <<"sizeof(s + 'b') = "<<sizeof(s +'b')<< endl;//int + int,int高效return0;}
转换构造函数
1.有且仅有一个参数
2.参数是基本类型
3.参数是其他类类型
explicit关键字杜绝编译器的转换尝试
explicit修饰的函数只能显示转换
static_cast(value)
(ClassName)(value)
#include<iostream>#include<string>usingnamespace std;classTest{int mValue;public:Test(){
mValue =0;}explicit Test (int i)//转换构造函数1.有且仅有一个参数2.参数是基本类型3.参数是其他类型{
mValue = i;}
Test operator+(const Test& p)//重载加法操作符函数{
Test ret(mValue + p.mValue);return ret;}intvalue(){return mValue;}};intmain(){
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;return0;}
转换构造函数
1.有且仅有一个参数
2参数是其他类类型
3.类型装换时被调用
explicit杜绝隐式类型转换
类类型转换函数
#include<iostream>#include<string>usingnamespace std;classTest{int mValue;public:Test(int i =0){
mValue = i;}intvalue(){return mValue;}operatorint()//类类型转换函数{int ret = mValue;return mValue;}};intmain(){
Test t(100);int i = t;//==>>int i = t.operator int();
cout <<"t.value() = "<< t.value()<< endl;
cout <<"i = "<< i << endl;return0;}
类转类型函数
#include<iostream>#include<string>usingnamespace std;classTest;classValue{public:Value(){}explicitValue(Test& t){}};classTest{int mValue;public:Test(int i =0){
mValue = i;}intvalue(){return mValue;}//operator Value()//类类型转换函数
Value toValue(){
Value ret;
cout <<"operator Value()"<< endl;return ret;}};intmain(){
Test t(100);//Value v = t;//v= t.operator Value(); //==>Value(t) //Value v = t.toValue();return0;}