How does while (std::cin >> value) work?

前端 未结 3 1282
逝去的感伤
逝去的感伤 2021-01-18 05:29

In an example given in C++ Primer,

#include 
using namespace std;

int main() {
    int sum = 0, value = 0;  
    while (std::cin >> va         


        
3条回答
  •  无人共我
    2021-01-18 06:14

    C++ translates this line

    while (std::cin >> value)
    

    to something like

    inline bool f(int v) {
      auto& i = std::cin >> v;
      return i.operator bool();
    }
    
    while( f(v) ) {
    

    Why it translates to bool? Because while expects a boolean expression, so compiler search for the boolean conversion operator of the return of std::cin >> v.

    What is a bool conversion operator? Boolean conversion operator translates the object to bool. If some part of the code expect to some type to work a as boolean (like casting) then this operator is used.

    What is an operator? Is a function or method that override the behavior of some operationg expressions (+, -, casting, ->, etc)

提交回复
热议问题