看下面這個類Fun ,其中包括了構造函數和類型強制轉換函數。
1. #include <iostream>
2. #include <cstdio>
3. #include "fun.h"
4. using namespace std;
5. int main()
6. {
7. Fun f;
8. cout << f << endl;//輸出5
9. printf("%d\n", f);//輸出3
10. printf("$d\n", (int)f);//輸出5 11. return 0; }
不難看出,<<的調用將第二個參數強制轉換為int,但是printf的%d只是讀取了後面參數的前32位,解析成為int。如果需要用printf並且調用類的強制轉換方法,需要顯式的將對象進行類型的強制轉換。