2015-01-22 1 views
-3

C++에서는 참조를 다시 지정하고 다른 객체에 경계를 지정하는 것이 좋습니다. 그러나 아래 코드는 컴파일 할 수 없습니다.istream/ostream에 대한 참조를 다시 할당 할 수없는 이유는 무엇입니까?

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 
     ^
+1

"그것은 또 다른 객체에 경계, 참조를 다시 할당 괜찮아 ++ C에서."** 잘못된 **. – juanchopanza

+0

대답은 여기에 있어야합니다 : http://stackoverflow.com/questions/8070537/how-should-i-correctly-assign-cout-to-a-static-ostream-reference-variable?rq=1 – stefan

+0

아니요 여기에 : http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list –

답변

3

C++에서는 참조를 다시 할당하고 다른 객체에 경계를 지정하는 것이 좋습니다.

아니,

이 사람이 뭐가 잘못 됐는지 말해 줄 수없는?

C++에서는 다른 개체에 바인딩하기 위해 참조를 다시 할당 할 수 없습니다. 참조는 다른 객체의 별칭입니다. 참조를 "할당"하면 참조가 참조하는 객체를 변경하지 않고 참조 된 객체에 지정합니다. 예를 들어

:

flag 

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

미안. 나는 그렇게 생각했다. 하지만 왜 다음 코드를 컴파일 할 수 있습니까? – Warbean

+0

int a = 3, b = 4; int & ref = a; ref = b; – Warbean

+0

죄송합니다. 지금은 이해하고 있습니다 ... – Warbean

3

참조가 개체에 바인딩되어 있으므로 다시 할당 할 수 없습니다.

참조는 생성시 초기화 된 별명으로 남아 있습니다.