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 \