10. explicit 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. operator int() const 28. {
29. return int( 100.5 );
30. }
31. operator double() const 32. {
33. return 999.5 ; 34. } 35. private:
36. enum { Lbs_per_stn = 14 }; 37. int m_nStone; 38. double m_fPds_left; 39. double m_fPounds; 40. }; 41. } 42.
43. int _tmain(int argc, _TCHAR* argv[]) 44. {
45. CStonewt myCat;
46. myCat = (CStonewt)19.5; 47. double fValue = myCat; 48. int iValue = myCat;
49. cout << \:\<< iValue << endl; 50. cout << \:\<< fValue << endl; 51.
52. return 0; 53. }
类和动态内存分配
小插曲 : strlen()返回字符串长度,但不包括末尾的空字符,因此构造函数len + 1,使分配的内存能够存储包含空字符的字符串 1)含有很多隐藏错误的stringBad类 StringBad.h:
[cpp] view plaincopyprint?
1. #ifndef _STRINGBAD_H_ 2. #define _STRINGBAD_H_ 3.
4. #include \ 5. #include \ 6. using namespace std; 7.
8. class StringBad 9. { 10. public:
11. StringBad();
12. StringBad( const char* str );
13. ~StringBad(); 14.
15. friend ostream& operator<< ( ostream& os, const StringBad& sb ); 16. private:
17. char* m_str; 18. int m_nLen; 19. public:
20. static int num_strings; 21. }; 22. 23. #endif
StringBad.cpp:
[cpp] view plaincopyprint?
1. #include \ 2. #include \ 3.
4. int StringBad::num_strings = 0; 5.
6. StringBad::StringBad() 7. {
8. m_nLen = 4;
9. m_str = new char[ 4 ]; 10. num_strings++;
11. strcpy_s( m_str, strlen( \ ) + 1,\ );
12. cout << StringBad::num_strings << \ << m_str << \ << endl; 13. } 14.
15. StringBad::StringBad( const char* str ) 16. {
17. m_nLen = strlen( str );
18. m_str = new char[ m_nLen + 1 ]; 19. num_strings++;
20. strcpy_s( m_str,m_nLen + 1 , str );
21. cout << num_strings << \ << m_str << \object created\ << endl; 22. } 23.
24. StringBad::~StringBad() 25. {
26. if ( m_str )