2015-10-17 75 views
1

我已經實現了一個重載的Shift運算符,它需要輸出流作爲參數。在另一個類中,我正在處理這個函數,該函數返回重載運算符的輸出流。模板:不兼容列表迭代器

該類包含車輛列表,我想返回包含這些車輛名稱的流。

std::ostream& classname::outputprint(std::ostream& outputstream) const 
{ 
    typedef std::list <Vehicles*>::iterator itType; 
    itType it3; 
    outputstream << std::setw(9) << name; 

    for(cVehicles.begin() = it3; cVehicles.end() != it3 ; ++it3) 
    { 
     outputstream << std::setw(4) << (*it3)->getName(); 
    } 
    return outputstream; 
} 

在頭文件,集裝箱聲明如下:

std::list<Vehicles*> cVehicles; 

當我嘗試啓動該程序出現錯誤: 「表達式:列表迭代不兼容」

有人可以向我解釋爲什麼我得到這個錯誤,以及如何解決這個問題?

此外,我試圖改變for循環的:

for(it3 = cVehicles.begin(); cVehicles.end() != it3 ; ++it3) 
{ 
... 
} 

這裏PROGRAMM根本不能編譯,我得到的錯誤: 「沒有‘=’操作這些操作數相匹配」。簡單的轉換如何對程序產生這樣的影響?

我會很感激任何形式的幫助,提前致謝!

+0

更改爲'typedef std :: list :: const_iterator itType;' –

+0

'class :: outputprint'應該是什麼意思?無論如何,'cVehcles'是您試圖展示其成員函數的類的數據成員嗎? – juanchopanza

+0

cVehicles是列表容器。聲明在上面,其要素是車輛指針。 class :: outputprint返回輸出流,它將用於重載「<<」運算符。 – AlTrain

回答

1

假設cVehicles是一個成員變量,那麼它是const。你需要一個const_iterator來迭代它。

第二個問題是您在函數中的for循環中顛倒了您的賦值。

你得到的最後一個錯誤是因爲迭代器問題。 begin()返回一個const_iterator,它不能被分配到iterator。另一種方式是可以的,但不是非const的const。

+0

所以在for循環中迭代變量必須站在同一側? 例如for(it1 = cVehicles.begin(); it1!= cVehicles.end(); it1 ++)就可以!對於(cVehicles.begin()= it1; it1!= cVehicles.end(); it1 ++) 和for(it1 = cVehicles.begin(); cVehicles.end()!= it1; it1 ++) 好? – AlTrain

+0

進一步爲什麼是cVehicles常量?我剛剛宣佈了一個私人列表容器。對不起,但我從來沒有面對過一個const_iterator。 – AlTrain

+0

第一和第三都很好。你不能分配給右值,所以秒數不在。 cVehicles是const,因爲使用它的函數是const的,我假設它是一個成員變量。如果不是,那麼我不知道 - 你沒有分享這個代碼。 –