设为首页 加入收藏

TOP

5.3.2 Using the Shift Operators for IO
2013-10-07 15:22:45 来源: 作者: 【 】 浏览:60
Tags:5.3.2 Using the Shift Operators for

The IO library redefines the bitwise >> and << operators to do input and output. Even though many programmers never need to use the bitwise operators directly, most programs do make extensive use of the overloaded versions of these operators for IO. When we use an overloaded operator, it has the same precedence and associativity as is defined for the built-in version of the operator. Therefore, programmers need to understand the precedence and associativity of these operators even if they never use them with their built-in meaning as the shift operators.

The IO Operators Are Left Associative

Like the other binary operators, the shift operators are left associative. These operators group from left to right, which accounts for the fact that we can concatenate input and output operations into a single statement:

  1. cout << "hi" << " there" << endl; 

executes as:

  1. ( (cout << "hi") << " there" ) << endl; 

In this statement, the operand "hi" is grouped with the first << symbol. Its result is grouped with the second, and then that result is grouped to the third.

The shift operators havemidlevel precedence: lower precedence than the arithmetic operators but higher than the relational, assignment, or conditional operators. These relative precedence levels affect how wewrite IO expressions involving operands that use operators with lower precedence. We often need to use parentheses to force the right grouping:

  1. cout << 42 + 10; // ok, + has higher precedence, so the sum is printed  
  2. cout << (10 < 42); // ok: parentheses force intended grouping; prints 1  
  3. cout << 10 < 42; // error: attempt to compare cout to 42! 

The second cout is interpreted as

  1. (cout << 10) < 42; 

this expression says to “write 10 onto cout and then compare the result of that operation (e.g., cout) to 42.”

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.9.2 A Brief Introduction to t.. 下一篇5.3.1 Using bitset Objects or I..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: