如何在 c++ 中打印存档中的对象向量

How to print a vector of objects from an archive in c++

本文关键字:对象 向量 打印 c++      更新时间:2023-10-16

我的代码应该读取一个文件,并从该文件上的信息创建类 Movie 和 将它们存储在矢量中,现在它们在矢量中,我如何打印这些对象?

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对象中。