標準數據類型之間會進行隱式的類型轉化
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;
}