問題:
類類型是否可以類型轉換到普通類型呢?ios
#include <iostream> using namespace std; class Test { }; int main() { Test t; int i = 0; i = t; return 0; }
輸出: test.cpp: In function ‘int main()’: test.cpp:14: error: cannot convert ‘Test’ to ‘int’ in assignment
- C++ 類能夠定義類型轉換函數
- 類型轉換函數用於將類對象轉換爲其它類型
語法規則:編程
operator Type () { Type ret; // ... return ret; }
#include <iostream> using namespace std; class Test { private: 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; // <==> int i = t.operator int (); cout << "t.value() = " << t.value() << endl; cout << "i = " << i << endl; return 0; }
輸出: t.value() = 100 i = 100
- 編譯器會盡力嘗試讓源碼經過編譯
t 這個對象爲 Test 類型,怎麼可能用於初始化 int 類型的變量呢!如今就報錯嗎?不急,我看看有沒有類型轉換函數!OK,發現 Test 類中定義了 operator int () ,能夠進行轉換。函數
類型轉換函數spa
- 與轉換構造函數有同等的地位
- 使得編譯器有能力將對象轉化爲其它類型
- 編譯器可以隱式的使用類型轉換函數
類類型之間的相互轉換?!
類型轉換函數 VS 轉換構造函數code
#include <iostream> using namespace std; class Test; class Value { public: Value() { } explicit Value(Test& t) { } }; class Test { public: operator Value () { Value ret; cout << "operator Value ()" << endl; return ret; } }; int main() { Test t; Value v = t; // <==> Value v = t.operator Value (); return 0; }
輸出: operator Value ()
注意:
當 Value 類中 Value(Test& t) {} 不使用 explicit 修飾,在編譯時將與 Test 類中的 operator Value () 產生匹配衝突。對象
error: conversion from ‘Test’ to ‘Value’ is ambiguous note: candidates are: Test::operator Value() note: Value::Value(Test&)
- 沒法抑制隱式的類型轉換函數調用(當定義後)
- 類型轉換函數可能與轉換構造函數衝突
- 工程中以
Type toType()
的公有成員代替類型轉換函數
#include <iostream> using namespace std; class Test; class Value { public: Value() { } explicit Value(Test& t) { } }; class Test { public: Value toValue () // 注意這裏! { Value ret; cout << "operator Value ()" << endl; return ret; } }; int main() { Test t; Value v = t.toValue(); return 0; }
輸出: operator Value ()
工程中不推薦使用類型轉換函數。隱式的類型轉換可能會產生意想不到的問題。ci
- C++ 類中能夠定義類型轉換函數
- 類型轉換函數用於將類對象轉換爲其它類型
- 類型轉換函數與轉換構造函數具備同等的地位
- 工程中以
Type toType()
的公有成員函數代替類型轉換函數
以上內容參考狄泰軟件學院系列課程,請你們保護原創!編譯器