【发布时间】:2020-04-29 14:33:16
【问题描述】:
我在将对象推回对象列表时遇到问题。
std::ostream& operator << (std::ostream& os, const Class1& sk) {
os << sk.X << 'x' << sk.Y << 'x' << sk.H << ';' << sk.a << ';' << sk.b << '\n';
return os;
}
std::istream& operator >> (std::istream& is, Class1& sk) {
char ch;
is >> sk.X >> ch >> sk.Y >> ch >> sk.H >> ch >> sk.a >> ch >> sk.b >> ch;
return is;
}
void Class1::GetSK_list(std::list<Class1>& SK_list) {
std::ifstream file("file.txt", std::ios::in);
std::list<Class1>::iterator iter = SK_list.begin();
while(file >> *iter) {
"std::cout << *iter"; // checking
SK_list.push_back(*iter);
iter++;
}
file.close();
}
void Class1::SaveSK_list(std::list<Class1>& SK_list) {
std::ofstream file("file.txt", std::ios::out);
for(std::list<Class1>::iterator iter = SK_list.begin(); iter != SK_list.end(); iter++)
file << *iter;
file.close();
}
当我使用 SaveSK_list 函数时,它可以正常工作。
问题出在 GetSK_list 函数上。如果文件中有一行(例如 1x2x3;4;5)文件 >> *iter 不起作用。没有打印任何内容(我相信 std::cout
如果文件中有多行,则只打印第一行。 After that std::bad_alloc error appears.
顺便说一句。这些函数都在 Class1 中,以便使用运算符重载。
【问题讨论】:
-
如果在调用
GetSK_list时SK_list为空,那么file >> *iter将是未定义的行为。即使它不是空的,你的循环也没有多大意义。 -
"std::cout << *iter".... 尝试不使用"。如果那是代码,您将看不到std::cout的输出 -
而不是
while(file >> *iter)(这是问题),读入Class1(例如Class1 temp;)和file >> temp的实例,然后调用.push_back(temp); -
"(我相信 std::cout 使用您的调试器,确定。
标签: c++ list oop object operator-overloading