UFO ET IT

cout 및 cin에 비트 시프트 (<< 및 >>)가 사용되는 이유는 무엇입니까?

ufoet 2020. 11. 17. 21:29
반응형

cout 및 cin에 비트 시프트 (<< 및 >>)가 사용되는 이유는 무엇입니까?


질문은 정말 제목에 있습니다. 논리적 인 것이 있다고 확신하지만 지금은 당황합니다!


The Design and Evolution of C ++의 §8.3.1에 따르면 :

Doug McIlroy는 명명 된 출력 함수 대신 출력 연산자를 제공한다는 아이디어를 UNIX 셸 (>, >>, | 등)의 I / O 리디렉션 연산자와 유사하게 제안했습니다.

[...]

입력 및 출력 작업에 대해 여러 연산자가 고려되었습니다. "할당 연산자는 입력과 출력 모두에 대한 후보 였지만 잘못된 방식으로 바인딩됩니다. 이는 cout=a=b로 해석되며 cout=(a=b)대부분의 사람들은 입력 연산자가 다음과 다른 것을 선호하는 것 같습니다. 연산자 <>시도를했지만 "보다 작음"및 "보다 큼"이라는 의미가 사람들의 마음에 너무 확고하게 이식되어 새로운 I / O 문을 모든 실제적인 목적을 위해 읽을 수 없었습니다. 그 외에도 대부분의 키보드에서 '<'는 ','바로 위에 있으며 사람들은 다음과 같은 표현을 작성했습니다.

cout < x , y, z;

이에 대한 좋은 오류 메시지를 제공하는 것은 쉽지 않습니다.


기본적으로 입력 / 출력 스트림에 추가하므로 Unix 추가 작업과 비슷해 보일 수 있습니다.

산출

echo "foo" >> bar

입력

sendmail -f test@domain.com << myemail.txt

(Zac Howland의 스톨 입력 예)


"C ++ 프로그래밍 언어"에서. Stroustrup의 (언어 저자) 단어 :

연산자 <<를``넣다 ''를 의미하도록 오버로딩하면 더 나은 표기법을 제공하고 프로그래머가 단일 명령문에서 일련의 객체를 출력 할 수 있습니다.

하지만 왜 <<? 새로운 어휘 토큰을 만드는 것은 불가능합니다. 할당 연산자는 입력과 출력 모두에 대한 후보 였지만 대부분의 사람들은 입력과 출력에 대해 다른 연산자를 사용하는 것을 선호하는 것 같습니다. 또한 =는 잘못된 방식으로 묶습니다. 즉, cout = a = b는 (cout = a) = b가 아니라 cout = (a = b)를 의미합니다. 나는 통신을 시도 <하고 >있지만, 평균 ''보다 ''와 ''보다 ''너무 단단히 새 I / O 문을 읽을 모든 실제적인 목적이라고 사람들의 마음에 이식했다.


>>그리고 <<단지 사업자이고, 당신이 자신을 구현할 수 >><<수업합니다.

a) 쉘 파일 작업과 유사하고 b) 새 연산자를 만들 필요가 없기 때문에 기존 연산자를 재사용하기 때문에 "누군가"가 이들을 선택했다고 가정합니다.


그들은 다소 합리적인 우선 순위를 가지고 있고 좋아 보였기 때문입니다. C ++에서는 새 연산자를 만들거나 우선 순위 또는 그룹화 규칙을 변경할 수 없으며 기존 연산자를 오버로드하고 실제로 수행하는 작업 만 변경할 수 있습니다.

<<and 의 선택은 >>결과가 순서에 따라 수행 될 것이라는 생각을 어떻게 든 밀어 붙이기 때문에 불행한 부작용이 있습니다. 이것은 영리한 체인 트릭 덕분에 실제 출력에 대해 사실이지만 관련된 계산에는 거짓이며 이것은 종종 놀라운 일입니다.

더 구체적인 글쓰기

std::cout << foo() << bar() << std::eol;

foo이전에 호출 될 것이라는 의미는 아닙니다 bar.

편집하다

C ++ 17에서는 시퀀스 문제가 "수정"되었습니다. 이제 평가 순서는 <<>>연산자에 대해 왼쪽에서 오른쪽으로 지정됩니다 . 평가 순서가 지정되어 있지 않은 C의 장소 ++ 여전히있다 (심지어는 존재하지 않는 인터리브 할 수있는 평가를 의미)하지만, 몇 가지 일반적인 경우 지금보고 예측 가능하고 휴대용 방식으로 행동 이 대답을 .


따라서 cin키보드와 cout모니터로 생각하면 입력 한 내용이 변수

cin>>var;

또는 변수의 내용이 화면으로 이동합니다.

cout<<var;

이 연산자는 비트 연산자가 아니며이 컨텍스트에서는 삽입 및 추출 연산자라고합니다.

http://www.cplusplus.com/doc/tutorial/basic_io/

시각적 해석에만 사용됩니다. 자체 스트림 개발 및 연산자 오버로딩을 연구하면 입력에 +를 사용하고 출력에-를 사용할 수도 있음을 알 수 있습니다. :)


이 대답은 만족스럽지 않지만 정확합니다. 비트 연산자가 아닙니다.

연산자의 의미는 왼쪽에 나타나는 데이터 유형에 따라 결정됩니다. cin 및 cout (및 기타 스트림 유형)의 경우 << 및 >> 연산자는 스트림간에 값을 이동합니다. 왼쪽 피연산자가 정수인 경우 연산은 C에서 이미 알고있는 비트 연산입니다.

연산자의 의미는 고정되어 있지 않지만 우선 순위가 있습니다.


대부분의 연관성 때문입니다. 삽입 및 추출 연산자는 왼쪽에서 오른쪽으로 연결되므로

std::cout << "Hello" << ' ' << 4 << 2;

는 예상대로 평가됩니다. 처음에는으로 "Hello", 다음으로 ' ', 마지막으로 4및으로 평가 2합니다. 물론 더하기 연산자 operator+도 왼쪽에서 오른쪽으로 연결됩니다. 그러나 그 연산자와 왼쪽에서 오른쪽으로의 연관성을 가진 다른 사람들은 이미 다른 의미를 가지고 있습니다.


Bjarne은 실용적인 우선 순위, 연관성 및 니모닉 값으로 이들을 선택했습니다.

우선 순위가 완벽하지 않습니다. 예를 들어 부울 및 비트 수준 연산자가 문제가됩니다.

하지만 괜찮습니다.


Insertion operator >> and << are used with Input Stream and Output Stream respectively because Input stream means flow of data into your program and Output stream means flow of data out of your program. As these insertion operators look like Directional operator (Showing direction of flow of data), so >> is chosen for Input stream and << for the Output stream.

Have a look at the part of code...

int Num1;
cin >> Num1;

here if you observe carefully >> is showing flow of data to variable (declared in program) that means the flow of data to the program , which is a job of Input stream (here cin).

similarly goes with cout,

int Num2 = 5;
cout << Num2;

Here << showing the flow of data out of the program (as Num2 is part of the program), which is the job of Output stream.

I hope all this make sense to you.


cout << "Output sentence"; // prints Output sentence on screen
cout << 120;               // prints number 120 on screen
cout << x;                 // prints the content of x on screen 

The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the constant string Output sentence, the numerical constant 120 and variable x into the standard output stream cout.

The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example:

int age;
cin >> age;

I assume that you are aware that C++ allows for operator overloading. In general, you overload operators only if the semantics are completely transferable (e.g. overloading the addition for a vector class to add two vectors together). I think your question refers to why one would use bitshift operators, overload them for the iostream, and give them a completely different meaning than their original purpose. The reason it can be done is because bitshift operations are so far removed from what iostreams do that no one could be confused into thinking that << or >> is doing a bitshift on an iostream. And the reason why they are convenient to use also is that their ordering is to evaluate the operand on the left first, then the one on the right, and do the operation. This fits to what you would want to happen when you are using the operators to append or extract stuff from an iostream.

But, to the original question, why? I don't really know, it just seems to me like the << and >> are pretty easily understood as taking information from one entity and putting it in the other. Why does the reason need to be more complicated than that? It looks sensible to use those because their meaning is obvious.. what better could you ask of an operator?

참고URL : https://stackoverflow.com/questions/4854248/why-are-bitwise-shifts-and-used-for-cout-and-cin

반응형