我正在为一个类编写一个程序,它有一个虚拟输出函数和一个迭代器,它可以输出到具有特定逻辑的屏幕或输出到具有特定逻辑的文件。我遇到的问题是它在应该调用 else 的情况下调用了 IF 部分。想知道是否有人可以阐明这一点。
调用输出函数:
ofstream fout;
fout.open("save.txt");
if (!fout.fail()){
for (list<pethousedotcom*>::iterator it = homelist.begin(); it != homelist.end(); it++)
(*it)->output(fout); //<-- calling function below still calling the one that is only supposed to be for cout
输出函数:
void bird::output(ostream& os) const {
if (os == cout) {
//still being executed
}
else {
// being skipped
}
}
这里有什么明显的错误吗?或任何建议?
最佳答案
"Anything obvious wrong here?"
假设你的文件打开成功,语句
if (os == cout) {
//still being executed
}
只是比较the state (results of the std::basic_ios::operator void*()
)这两个 std::ostream
实例的计算结果很可能对它们都为 true
。
"any advice?"
如果你想区分os
实际上等于cout
你可以比较他们的地址:
if (&os == &cout) {
// not being being executed when writing to std::cout
}
关于c++ - 使用和 if/else 语句输出到屏幕或文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333367/