[英]How to print a vector of objects from an archive in c++
我的代碼應該讀取一個文件,並從該文件上的信息中創建 class 電影的對象並將它們存儲在向量中,既然它們在向量中,我該如何打印這些對象?
void Movie::loadFile(string file)
{
ifstream inFile;
inFile.open(file+".txt");
try {
if (!inFile)
throw "UNABLE TO OPEN FILE";
}catch (const char* msg)
{
cerr << msg << endl;
exit(1);
}
while (inFile.good())
{
getline(inFile, id, ',');
getline(inFile, name, ',');
getline(inFile, tim, ',');
getline(inFile, gen, ',');
getline(inFile, rate, '\n');
mov.push_back(new Movie(id, name, tim, gen, rate));
}
inFile.close();
cout<<endl;
}
我試圖通過重載運算符來做到這一點,但我得到了錯誤
error: 'std::vector<Movie*> Movie::mov' is protected within this context
error: 'ostream_iterator' was not declared in this scope
error: expected primary-expression before '>' token
ostream &operator <<(ostream& salida, const Movie& print)
{
salida << print.id << endl;
copy(print.mov.begin(), print.mov.end(), ostream_iterator<Video>(salida, " "));
return salida;
}
我真的很感激幫助:)。
為了使用
copy(print.mov.begin(), print.mov.end(), ostream_iterator<Video>(salida, " "));
您需要實現以下重載。
std::ostream& operator<<(std::ostream&, Video const&);
從https://en.cppreference.com/w/cpp/iterator/ostream_iterator :
std::ostream_iterator
是一個單通道LegacyOutputIterator ,它使用operator<<
將T
類型的連續對象寫入為其構造的std::basic_ostream
object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.