2016-12-30 39 views
1

我試圖做如何複製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 

什麼是做這種正確的方法是什麼?

+7

掛上一秒......你爲什麼要「複製」std :: cin? – WhiZTiM

+1

「做這件事的正確方法是什麼?」不這樣做。 – YSC

+0

「但編譯器只給了我不可理解的錯誤」:它基本上是說''ios_base'拷貝構造函數是私有的,你不能複製它。 – Amadeus

回答

2

標準分類std::istream不可複製。你可以聲明一個參考std::cin例如通過以下方式

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

或者你可以寫

auto &cin2 = std::cin; 

要實現你可以用引用或指針到流的istream的迭代器。

+0

不會'auto&cin2 = cin;'更具可讀性且不易出錯? – Rakete1111

+0

@ Rakete1111像往常一樣,有幾種方法可以完成一項任務:) –

+0

由於分類方式的奇怪類型推斷,在使用'decltype(auto)'時分配時很容易忘記parens,這就是爲什麼我想知道爲什麼你使用方式:)但哦哦 – Rakete1111