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

Why cannot re-assign to a reference to istream / ostream?

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

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
           ^

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

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

In C++ it's alright to re-assign a reference, bounding it to another object.

不,不是

Can anybody tell me what's wrong?

在 C++ 中,您不能重新分配引用以将其绑定到另一个对象。引用是另一个对象的别名。如果您 "assign" 一个引用,您是在分配给被引用的对象,而不是更改引用所引用的对象。

例如:

flag

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