通过引用传递std :: istream和std :: ostream以便在函数内使用

时间:2020-09-05 17:02:24

标签: c++

我正在尝试使用以下功能:

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;
}

错误:

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

完整错误,这是我在调试和编译该错误时遇到的全部错误,

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)导致以下错误:

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

1 个答案:

答案 0 :(得分:3)

看看std::istream constructorstd::ostream constructor以及示例。

您要这样做:

#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

代替此:

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;
}

该错误消息是因为您无法访问std::istreamstd::ostream的默认构造函数,因此受到保护:

basic_istream:

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

basic_ostream:

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