我有一段簡單的代碼給了我一個編譯器錯誤。我沒有問題編譯和運行在Visual Studio下的Windows環境下,但現在在Linux下,使用gcc,我有問題。注意我正在使用gcc 4.4.5,並使用-std = C++ 0x指令。編譯器在使用GCC的代碼上出現錯誤代碼
該代碼片段位於頭文件file_handling.h中,該文件包含所有必需的庫(vector,string,fstream等)。變量'output_file'是LogFile對象的成員,並在其他地方正確檢查/實例化/ etc。代碼本身是平凡簡單,這就是爲什麼我很爲難:
template <typename T> void LogFile::put(std::string const & header, std::vector<T> const & data) {
output_file << header << " " << std::scientific << data[0] << std::endl;
for (std::vector<T>::const_iterator value = (data.begin()+1); value < data.end(); ++value) {
output_file << *value << std::endl;
}
}
編譯器狀態:
In file included from file_handling.cpp:2:
file_handling.h: In member function 'void LogFile::put(const std::string&, const std::vector<T, std::allocator<_Tp1> >&)':
file_handling.h:132: error: expected ';' before 'value'
file_handling.h:132: error: 'value' was not declared in this scope
make: *** [file_handling.o] Error 1
爲什麼GCC沒有看到「價值」的原位聲明爲常量性?我已經嘗試了以下作爲完整性檢查:
template <typename T> void LogFile::put(std::string const & header, std::vector<T> const & data) {
std::vector<T>::const_iterator value;
output_file << header << " " << std::scientific << data[0] << std::endl;
for (value = (data.begin()+1); value < data.end(); ++value) {
output_file << *value << std::endl;
}
}
並且接收完全相同的編譯器報告。鑑於這看起來很簡單,並且在Visual Studio中運行良好,我對gcc和/或Linux環境有何遺漏或誤解?
'#include'? –
我假設矢量會爲我提供迭代器,因爲:: const_iterator是它的一個屬性,並且它一直在Visual Studio中工作。也就是說,我只是添加它來測試你的想法,不幸的是,這並沒有解決它。好主意,但。 – Avacar
嘗試cbegin()而不是begin()。 begin()不適用於const迭代器。你還需要cend()而不是end()。 –