下面的代码来自c++ primer plus第5版第12章,书中代码写的非常好:
// string1.h -- fixed and augmented string class definition #include <iostream> using std::ostream; using std::istream; #ifndef STRING1_H_ #define STRING1_H_ class String { private: char * str; // pointer to string int len; // length of string static int num_strings; // number of objects static const int CINLIM = 80; // cin input limit public: // constructors and other methods String(const char * s); // constructor String(); // default constructor String(const String &); // copy constructor ~String(); // destructor int length () const { return len; } // overloaded operator methods String & operator=(const String &); String & operator=(const char *); char & operator[](int i); const char & operator[](int i) const; // overloaded operator friends friend bool operator<(const String &st, const String &st2); friend bool operator>(const String &st1, const String &st2); friend bool operator==(const String &st, const String &st2); friend ostream & operator<<(ostream & os, const String & st); friend istream & operator>>(istream & is, String & st); // static function static int HowMany(); }; #endif
num_strings 主要是为了统计对象创建的个数.
cpp文件:
// string1.cpp -- String class methods #include <cstring> // string.h for some #include "string1.h" // includes <iostream> using std::cin; using std::cout; // initializing static class member int String::num_strings = 0; // static method int String::HowMany() { return num_strings; } // class methods String::String(const char * s) // construct String from C string { len = std::strlen(s); // set size str = new char[len + 1]; // allot storage std::strcpy(str, s); // initialize pointer num_strings++; // set object count } String::String() // default constructor { len = 4; str = new char[1]; str[0] = '