I am trying to implement a class in which I can't use cin and cout directly. I need to pass reference of input and output streams to the constructor of class and save them in some private fields so that I can access them later in some other function of a class. How can I achieve this functionality?
Why not simply use a reference to std::istream
and std::ostream
?
struct X
{
std::ostream& os;
std::istream& is;
X( std::ostream& os_, std::istream& is_):os{os_}, is{is_}{}
void Func() { os << "Hallo" << std::endl; }
void Inp() { std::string s; is >> s; os << s << std::endl; }
};
int main()
{
X x(std::cout, std::cin);
x.Func();
x.Inp();
}
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.