设为首页 加入收藏

TOP

5.12.3 Other Implicit Conversions (2)
2013-10-07 15:24:57 来源: 作者: 【 】 浏览:62
Tags:5.12.3 Other Implicit Conversions

Conversion to const

A nonconst object can be converted to a const object, which happens when we use a nonconst object to initialize a reference to const object. We can also convert the address of a nonconst object (or convert a nonconst pointer) to a pointer to the related const type:

  1. int i;  
  2. const int ci = 0;  
  3. const int &j = i; // ok: convert non-const to reference to const int  
  4. const int *p = &ci; // ok: convert address of non-const to address of a const 

Conversions Defined by the Library Types

Class types can define conversions that the compiler will apply automatically. Of the library types we’ve used so far, there is one important conversion that we have used. When we read from an istream as a condition

  1. string s;  
  2. while (cin >> s) 

we are implicitly using a conversion defined by the IO library. In a condition such as this one, the expression cin >> s is eva luated, meaning cin is read. Whether the read succeeds or fails, the result of the expression is cin.

The condition in the while expects a value of type bool, but it is given a value of type istream. That istream value is converted to bool. The effect of converting an istream to bool is to test the state of the stream. If the last attempt to read from cin succeeded, then the state of the stream will cause the conversion to bool to be true—the while test will succeed. If the last attempt failed—say because we hit end-of-file—then the conversion to bool will yield false and the
while condition will fail.

标准库std:istream 重载了14.9.2 节介绍的自定义转换操作符(细节:其转换的类型不是bool,而是void*,为的是避免误用,因为直接提供istream 到bool 的转换会让cin << 3 编译通过)。让一个class 类型的对象能隐式转换为bool 类型,可以用safe bool idiom。库的作者有必要了解这一技巧,应用程序的作者大可不必在意。

EXERCISES SECTION 5.12.3

Exercise 5.31: Given the variable definitions on page 180, explain what conversions take place when eva luating the following expressions:

(a) if (fval)

(b) dval = fval + ival;

(c) dval + ival + cval;

Remember that you may need to consider associativity of the operators in order to determine the answer in the case of expressions involving more than one operator.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.2 Literal Constants (2) 下一篇5.12.3 Other Implicit Conversio..

评论

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

·进入Linux世界大门的 (2025-12-24 14:51:47)
·Download Linux | Li (2025-12-24 14:51:44)
·Linux 指令初探:开 (2025-12-24 14:51:41)
·TCP连接失败的原因与 (2025-12-24 14:19:27)
·TCP Sever模式与TCP (2025-12-24 14:19:24)