如何复制cin

时间:2016-12-30 00:38:31

标签: c++ cin

我试着做

auto cin2 = cin;
int a;
cin2 >> a;

但编译器只给出了不可理解的错误:

/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/ios_base.h: In copy constructor ‘std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’:
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/ios_base.h:790: error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/iosfwd:47: error: within this context
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/iosfwd: In copy constructor ‘std::basic_istream<char, std::char_traits<char> >::basic_istream(const std::basic_istream<char, std::char_traits<char> >&)’:
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/iosfwd:53: note: synthesized method ‘std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’ first required here
test.cpp: In function ‘int main()’:
test.cpp:6: note: synthesized method ‘std::basic_istream<char, std::char_traits<char> >::basic_istream(const std::basic_istream<char, std::char_traits<char> >&)’ first required here

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

标准类std::istream不可复制。您可以通过以下方式声明对std::cin的引用

decltype(auto) cin2 = ( std::cin );
int a;
cin2 >> a;

或者你可以写

auto &cin2 = std::cin;

要实现istream迭代器,可以使用指向流的引用或指针。