c++ primer 学习笔记2

更新时间:2023-11-30 17:33:01 阅读量: 教育文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

<>读书笔记2

分类: IT书籍读书笔记2012-08-27 16:46 1019人阅读 评论(0) 收藏 举报

c++读书deleteiosstring 类的自动转换和强制类型转换

1)如果构造函数中含有类似的拷贝函数:

CStonewt( double lbs ) {

m_nStone = int( lbs ) / Lbs_per_stn;

m_fPds_left = int( lbs ) % Lbs_per_stn + lbs - int( lbs ); m_fPounds = lbs; }

那么使用 CStonewt myCat; myCat = 19;

程序将使用构造函数CStonewt( double lbs )来创建一个临时的CStonewt对象,并将19.6作为初始值。随后,采用逐成员赋值方式将该临时对象的内容赋值到myCat中(比如m_nStone = int(

lbs ) / Lbs_per_stn;)。这一过程称为隐式转换,因为他是自动进行的,而不需要显示强制类型转换。如果换成CStonewt( double lbs, int i )有两个参数,因此不能用来转换类型。

[cpp] view plaincopyprint?

1. #include \ 2. #include \ 3. using namespace std; 4.

5. namespace 6. {

7. class CStonewt 8. { 9. public:

10. CStonewt( double lbs ) 11. {

12. m_nStone = int( lbs ) / Lbs_per_stn; 13. m_fPds_left = int( lbs ) % Lbs_per_stn + lbs - int( lbs );

14. m_fPounds = lbs; 15. }

16. CStonewt( int stn, double lbs ) 17. {

18. m_nStone = stn; 19. m_fPds_left = lbs;

20. m_fPounds = stn * Lbs_per_stn + lbs; 21. }

22. CStonewt() 23. {

24. m_nStone = m_fPounds = m_fPds_left = 0;

25. }

26. ~CStonewt() 27. { 28.

29. }

30. void show_lbs() const 31. {

32. cout << m_nStone << \ << m_fPds_left << \ << endl;; 33. }

34. void show_stn() const 35. {

36. cout << m_fPounds << \ << endl; 37. } 38. private:

39. enum { Lbs_per_stn = 14 }; 40. int m_nStone; 41. double m_fPds_left; 42. double m_fPounds; 43. }; 44. }

45.

46. int _tmain(int argc, _TCHAR* argv[]) 47. {

48. CStonewt myCat; 49. myCat = 19; 50.

51. return 0; 52. }

2)将构造函数用作自动类型转换函数似乎是一项不错的特性。不过,当程序员拥有更丰富的C++经验时,将发现这种自动也行并非总是合乎需要的,因为这会导致意外的类型转换。因此,最新

的C++实现新增了一个关键字(explicit),用来关闭这种自动特性。也就是说,可以这样声明构造函数:

[cpp] view plaincopyprint?

1. explicit CStonewt( double lbs ) 2. {

3. m_nStone = int( lbs ) / Lbs_per_stn;

4. m_fPds_left = int( lbs ) % Lbs_per_stn + lbs - int( lbs );

5. m_fPounds = lbs; 6. }

但此时仍然可以进行myCat = (CStonewt)19.5;强制类型转换。 3)把CStonewt类对象赋值给int、double变量

要进行这样的操作时,编译器发现右侧是CStonewt类型,而左侧是int、double类型,因此它将查看程序员是否定义了与此匹配的转换函数(如果没有找到这样的定义,编译器将生成错误消息 ,指出无法将CStonewt赋给int、double)

如果想要使用这种转换函数,要转换为typeName类型,需要使用这种形式的转换函数: operator typeName(); 注意以下几点:

a、转换函数必须是类方法 b、转换函数不能指定返回类型 c、转换函数不能有参数

[html] view plaincopyprint?

1. #include \ 2. #include \ 3. using namespace std; 4.

5. namespace 6. {

7. class CStonewt 8. { 9. public:

本文来源:https://www.bwwdw.com/article/j1dt.html

Top