我正在使用抽象类std :: ostream.有以下参考:
std::ostream &o = std::cout;
Run Code Online (Sandbox Code Playgroud)
如果满足任何条件,我需要初始化o,以便输出重定向到std :: cout.如果没有,输出将被重定向到文件
if (!condition)
o = file; //Not possible
Run Code Online (Sandbox Code Playgroud)
如何正确编写代码?
Ste*_*sop 16
或者:
std::ostream &o = condition ? std::cout : file;
Run Code Online (Sandbox Code Playgroud)
或者如果两个代码段之间有代码:
std::ostream *op = &std::cout;
// more code here
if (!condition) {
op = &file;
}
std::ostream &o = *op;
Run Code Online (Sandbox Code Playgroud)
问题不是与抽象类有关,而是引用无法重新定位.
表达式的含义o = file不是"make orefer to file",而是"将值复制file到referand中o".幸运的是,std::ostream没有operator=,所以它无法编译,std::cout也没有修改.但考虑一下不同类型的情况:
#include <iostream>
int global_i = 0;
int main() {
int &o = global_i;
int file = 1;
o = file;
std::cout << global_i << "\n"; // prints 1, global_i has changed
file = 2;
std::cout << o << "\n"; // prints 1, o still refers to global_i, not file
}
Run Code Online (Sandbox Code Playgroud)
您无法重置参考.
这是另一种选择:
std::ostream &o = (!condition) ? file : std::cout;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
926 次 |
| 最近记录: |