2011-12-20 53 views
9

如果我需要從ifstream的投INT的地址正確的方式來字符指針

int myInt = 0; 
fileStream.read(reinterpret_cast<char*>(&myInt), sizeof(int)); 

讀INT使用reinterpret_cast<char*>正確的方式來實現這一目標?

+1

這可能是幫助:http://stackoverflow.com/questions/4748232/reinterpret-cast :) – 2011-12-20 13:48:41

+11

考慮使用'sizeof myInt'不能重複類型,並且如果稍後決定將類型更改爲eg,則是安全的'長'可能是一個不同的大小。 – unwind 2011-12-20 13:49:01

+1

謝謝。聽起來像是一個好主意'sizeof myInt' – dextrey 2011-12-20 13:55:09

回答

15

正在使用reinterpret_cast正確的方式來完成該操作嗎?

是的。更喜歡C++風格的轉換,而不是c風格轉換。

正如意見提出,用更好的方式read method function是:

int myInt = 0; 
fileStream.read(reinterpret_cast<char*>(&myInt), sizeof(myInt)); 
+0

我不同意答案(不是關於C++和c風格類型轉換的評論),請參閱Jon的答案。 – Walter 2011-12-20 14:19:19

+0

@Walter在左側有一個投票。但是,如果從二進制文件讀取Jon的答案,它的工作就不會起作用。 – 2011-12-20 14:25:52

+0

很遺憾,我無法編輯我那愚蠢的評論...... – Walter 2011-12-22 14:48:41