简体   繁体   中英

What's the point in passing I/O as parameters?

I am learning C++ Primer, Fifth Edition; and I still don't get it what's the point of passing a reference to a stream in the Sales_data class

Sales_data(std::istream &is)

Why do this if you can just use std::cout and std::cin explicitly?

You don't have to pass std::cin to such a function. You can also pass std::ifstream to read from a file, or std::istringstream to read from a string, and so on.

Why do this if you can just use std::cout and std::cin explicitly?

As a software design and implementation principle, it's better to have functions that don't use any hard coded objects and/or values.

When you make the std::istream object as input argument to the function, the function becomes flexible. The calling function(s) can decide whether they want to read the data from, which can come std::cin , a std::ifstream , a std::istringstream , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM