C 深度解析 32 型別轉換函式

2021-09-25 11:26:25 字數 1309 閱讀 5811

1.問題

2.型別轉換函式

operator type ()  

3.程式設計實驗

#include using namespace std;

class test

// 轉換建構函式 ,普通型別到類的型別轉換

test(int i = 0) // 只有建構函式才能被顯示宣告為explicit

// 型別轉換函式, 將類物件轉換為其他型別,這裡是int型別

operator int()

int value() };

int main()

4.型別轉換函式的意義

test t(1);

int i = t;

5.編譯器能夠隱式的使用型別轉換函式

#include using namespace std;

class test; // 前置宣告,因為要提前使用這個類

class value

//轉換建構函式,加了explicit就必須顯示的轉換型別,普通型別轉換到類型別。

explicit value(test &t) // 若不加explicit,則會報錯,兩個轉換函式都會隱式呼叫不知呼叫哪個

int value() };

class test

//轉換建構函式 , 普通型別到類型別的轉換

test(int i = 0)

// 型別轉換函式,類的物件轉換為其他型別

operator value()

int value() };

int main()

#include using namespace std;

class test; // 前置宣告,因為要提前使用這個類

class value

//轉換建構函式

value(test &t)

int value() };

class test

//轉換建構函式 , 普通型別到類型別的轉換

test(int i = 0)

int value()

value tovalue() };

int main()

6.小結

41 型別轉換函式

標準資料型別之間會進行隱式的型別安全轉換,規則如下 char short int unsigned int long unsigned long float double 小轉大 include include using namespace std int main else cout sizeo...

C 42 型別轉換函式 (下)

問題 類型別是否能夠型別轉換到普通型別呢?include using namespace std class test int main 輸出 test.cpp in function int main test.cpp 14 error cannot convert test to int in ...

42 型別轉換函式(下)

類型別是否能轉換為普通型別?c 類中可以定義型別轉換函式,型別轉換函式用於將類物件轉換為其它型別。語法規則 operator type 返回type型別 type ret return ret include include using namespace std class test int va...