-1

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?

  • What always will work is to take control over the internal buffer like described [here](https://stackoverflow.com/a/63968064/1413395) . The other option is to have `std::ostream` and `std::istream` reference members. But these will always need to be initialized correctly. – πάντα ῥεῖ Sep 25 '20 at 16:53

1 Answers1

1

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();
}
Klaus
  • 24,205
  • 7
  • 58
  • 113