简体   繁体   中英

Pass std::istream and std::ostream by reference to be used from within function

I am trying to consume the following function:

void f(std::istream& input, std::ostream& output) {
    int n;
    output << "enter a number: ";
    input >> n;
}

int main() {
    std::istream is;
    std::ostream os;
    f(is, os);
    return 0;
}

Error:

'std::basic_istream<_CharT, _Traits>::basic_istream()

Full error that's the entire error I am getting out when debugging and compiling this,

c:\Users\root\Documents\cpp\main.cpp: In function 'int main()':
c:\Users\root\Documents\cpp\main.cpp:40:18: error: 'std::basic_istream<_CharT, _Traits>::basic_istream() 
[with _CharT = char; _Traits = std::char_traits<char>]' is protected within this context
   40 |     std::istream in;
      |                  ^~
In file included from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\iostream:40,
                 from c:\Users\root\Documents\cpp\main.cpp:7:
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\istream:606:7: note: declared protected here
  606 |       basic_istream()
      |       ^~~~~~~~~~~~~
c:\Users\root\Documents\cpp\main.cpp:41:18: error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() 
[with _CharT = char; _Traits = std::char_traits<char>]' is protected within this context
   41 |     std::ostream out;
      |                  ^~~
In file included from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\iostream:39,
                 from c:\Users\root\Documents\cpp\main.cpp:7:
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ostream:390:7: note: declared protected here
  390 |       basic_ostream()
      |       ^~~~~~~~~~~~~

f(std::cin, std::cout) result in the error below:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid

Have a look at the std::istream constructor and the std::ostream constructor and example also.

You want to do this:

#include<iostream>

void f(std::istream& input, std::ostream& output)
{
    int n;
    output << "enter a number: ";
    input >> n;
}

int main()
{
    f(std::cin, std::cout);
    return 0;
}

Demo

instead of this:

void f(std::istream& input, std::ostream& output)
{
    int n;
    output << "enter a number: ";
    input >> n;
}

int main()
{
    std::istream is;   // Note: not linked to console
    std::ostream os;   // Note: not linked to console
    f(is, os);
    return 0;
}

The error message is because you can not access the default constructor of std::istream or std::ostream , it is protected:

basic_istream :

protected:
  basic_istream()
  : _M_gcount(streamsize(0))
  { this->init(0); }

basic_ostream :

protected:
  basic_ostream()
  { this->init(0); }

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