c++ primer 学习笔记2(3)

2018-12-09 17:03

27. {

28. delete[] m_str; 29. }

30. num_strings--;

31. cout << \rings is:\ << num_strings << endl; 32. } 33.

34. ostream& operator<< ( ostream& os, const StringBad& sb ) 35. {

36. os << \:\ << sb.m_str << endl;

37. os << \:\ << sb.m_nLen << endl; 38. return os; 39. }

testStringBad.cpp:

[cpp] view plaincopyprint?

1. #include \ 2. #include \

3. using namespace std; 4. #include \ 5.

6. void callme1( StringBad& rStringBad ) 7. {

8. cout << \ << endl; 9. cout << \ << rStringBad << endl; 10. } 11.

12. void callme2( StringBad stringBad ) 13. {

14. cout << \ << endl; 15. cout << \ << stringBad << endl; 16. } 17.

18. int _tmain(int argc, _TCHAR* argv[]) 19. {

20. StringBad headline1( \ ); 21. StringBad headline2( \ ); 22. StringBad sport( \ );

23.

24. cout << headline1 << endl; 25. cout << headline2 << endl; 26. cout << sport << endl; 27.

28. callme1( headline1 ); 29. cout << headline1 << endl; 30. callme2( headline2 ); 31. cout << headline2 << endl; 32.

33. cout << \:\ << endl;

34. StringBad sailer = sport;

35. cout << \ << sailer << endl; 36. cout << \:\ << endl; 37.

38. StringBad knot; 39. knot = headline1;

40. cout << \ << knot << endl; 41. cout << \ << endl; 42.

43. cout << \:

\ << StringBad::num_strings << endl; 44.

45. return 0; 46. }

2)

复制拷贝函数

[cpp] view plaincopyprint?

1. StringBad& StringBad::operator= ( const StringBad& st) 2. {

3. if( this == &st ) 4. {

5. return *this; 6. }

7. delete[] str; 8. len = st.len;

9. str = new char[ strlen( len + 1 ) ]; 10. str::strcpy( str, st.str ); 11. return *this; 12. }

3)

重写下标运算符

[cpp] view plaincopyprint?

1. char& operator[] ( int i ) 2. {

3. return m_str[ i ]; 4. }

5. const char& operator[] ( int i ) const 6. {

7. return m_str[ i ]; 8. }

为什么要提供两个版本。原因是m_str是常量,而上述方法无法确保不修改数据。

但在重载时,C++将区分常量和非常量函数的特征标,因此提供了另一个仅供const String对象使用的 operator[]()版本 4)

新的String类

[cpp] view plaincopyprint?

1. #include \ 2. #include \ 3. #include \


c++ primer 学习笔记2(3).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:师资管理制度汇编. - 华立学院

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: