2011-03-31 25 views
4

我試圖做這樣的事情:遞增的streampos對象

for (std::streampos Position = 0; Position < 123; Position++) 
{ 
    // Use Position to access something... 
} 

然而,似乎std::streampos沒有operator++超載。

嘗試使用Position = (Position + 1)導致以下錯誤:

ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: 

對此有什麼解決辦法呢,還是要依靠long unsigned int是用於文件夠大嗎?

回答

4

嘗試一個std::streamoff,它表示流中的偏移量。它支持前後增量/減量運算符。

The underlying type is implementation defined, but must be able to be consistently converted to both streamsize and fpos (thus, to streampos too)

編輯Maxpm的評論:您可以將streamoff在任何地方,無論是ios::beg或arbitary streampos。將其應用於ios::beg,它的行爲與正常的streampos相似。將它應用到streampos,你得到了streampos+streamoff

+0

流偏移量和流位置有什麼區別? – Maxpm 2011-03-31 15:06:13

+0

streampos是流中的位置。流失是與這樣一個位置的偏移。 :-) – 2011-03-31 16:52:31

+0

@Bo:Woops,完全忽略了Maxpm的評論,謝謝你抓住這個,馬克斯! ;) – Xeo 2011-03-31 16:55:31

3

使用+=

for (std::streampos Position = 0; Position < 123; Position += 1) 

+不會因爲operator +工作實際上是爲streampossteamoff,不int定義。

這意味着存在兩個同樣好的隱式轉換:您的1可能會轉換爲streamoff(這可能是unsigned long的typedef)。或者streampos被隱式轉換爲streamoff,然後1被添加。

2

std::streampos不是數值類型,雖然它支持將數字類型轉換爲 。如果您想對 位置進行算術運算,則需要使用std::streamoff(並且在調用seek時指定 參數)。

此外,不要忘記,您不能在 文件中尋找任意位置,除非它已經以二進制模式打開並且注入了「C」 區域設置。