为什么不能重新分配给istream / ostream的引用?

时间:2015-01-22 14:47:47

标签: c++ reference iostream

在C ++中sesms它可以重新分配一个引用,将它绑定到另一个对象。但是,下面的代码无法编译:

ostream &os_ref = cerr;
os_ref = cout;

有人可以告诉我什么是错的吗?错误信息如下所列。

temp.cpp: In function ‘int main()’:
temp.cpp:15:12: error: use of deleted function ‘std::basic_ostream<char>& std::basic_ostream<char>::operator=(const std::basic_ostream<char>&)’
     os_ref = cout;
            ^
In file included from /usr/include/c++/4.9/iostream:39:0,
                 from temp.cpp:1:
/usr/include/c++/4.9/ostream:58:11: note: ‘std::basic_ostream<char>& std::basic_ostream<char>::operator=(const std::basic_ostream<char>&)’ is implicitly deleted because the default definition would be ill-formed:
     class basic_ostream : virtual public basic_ios<_CharT, _Traits>
           ^
/usr/include/c++/4.9/ostream:58:11: error: use of deleted function ‘std::basic_ios<char>& std::basic_ios<char>::operator=(const std::basic_ios<char>&)’
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from temp.cpp:1:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: note: ‘std::basic_ios<char>& std::basic_ios<char>::operator=(const std::basic_ios<char>&)’ is implicitly deleted because the default definition would be ill-formed:
     class basic_ios : public ios_base
           ^
In file included from /usr/include/c++/4.9/ios:42:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from temp.cpp:1:
/usr/include/c++/4.9/bits/ios_base.h:789:5: error: ‘std::ios_base& std::ios_base::operator=(const std::ios_base&)’ is private
     operator=(const ios_base&);
     ^
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from temp.cpp:1:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: error: within this context
     class basic_ios : public ios_base
           ^

2 个答案:

答案 0 :(得分:3)

引用绑定到一个对象,你永远不能重新分配它。

引用保留为创建时初始化的别名。

答案 1 :(得分:3)

  

在C ++中,可以重新分配引用,将其绑定到另一个对象。

不,不是

  

有人可以告诉我什么错了吗?

在C ++中,您无法重新分配引用以将其绑定到另一个对象。引用是另一个对象的别名。如果你&#34;分配&#34;引用,您将分配给引用的对象,而不是更改引用引用的对象。

例如:

flag

int a = 3, b = 4;
int &ref = a;
ref = b;                     // like saying a = b;
std::cout << a << std::endl; // prints 4