【发布时间】:2017-01-26 18:17:23
【问题描述】:
我怎样才能使这个伪代码工作?
std::ostream ostr;
std::ofstream ofstr;
if(condition) {
ostr = std::cout;
}
else {
ofstr.open("file.txt");
ostr = ofstr;
}
ostr << "Hello" << std::endl;
这不会编译,因为std::ostream 没有公共默认构造函数。
【问题讨论】:
-
链接的问题不是完全重复的,但它足够接近,并且接受的答案显示了您的问题的解决方案。
-
在您的情况下,您可以使用三元运算符:
std::ostream& ostr = (condition ? std::cout : (ofstr.open("file.txt"), ofstr)); -
@Jarod42:刚试过;当
condition为真时它可以工作,并且我在 cout 上得到输出,但是当condition为假时我没有写入任何文件。 -
Demo.
标签: c++ stream iostream fstream ostream