h*****g 发帖数: 312 | 1 You have to implement a function that needs to be able to write to both
standard output (typically the console screen) and files. Which one of the
following function declarations satisfies that need?
A.
void print(std::ostream &os);
B.
void print(std::ofstream is);
C.
void print(std::cout);
D.
void print(std::istream is);
E.
void print(std::istream &is);
问下,B 为啥不行呢?A 可以输出到文件吗?网上没找到答案~~~ | s*****n 发帖数: 231 | 2 cout is an object of class ostream that represents the standard output
stream.
and ostream is the base class of ofstream, which you use to output to a file.
So in A. void print(std::ostream &os);
if you pass a reference to ostream object in the print function, it's OK for
both type.
But in B.void print(std::ofstream is);
Not only you cannot output to the standard output, but also it's passed by
value, that means you make a copy of the ostream object you passed in, and
do output in that copy, which may not work as expected.
Please correct me if I am wrong, thanks. | h*****g 发帖数: 312 | 3 thank you so much! I've learned a lot!
file.
for
【在 s*****n 的大作中提到】![](/moin_static193/solenoid/img/up.png) : cout is an object of class ostream that represents the standard output : stream. : and ostream is the base class of ofstream, which you use to output to a file. : So in A. void print(std::ostream &os); : if you pass a reference to ostream object in the print function, it's OK for : both type. : But in B.void print(std::ofstream is); : Not only you cannot output to the standard output, but also it's passed by : value, that means you make a copy of the ostream object you passed in, and : do output in that copy, which may not work as expected.
|
|