1、静态成员变量的初始化
静态成员变量声明在 .h 头文件文件中,初始化应该在 .cpp 源文件中
就会出现"找到一个或多个多重定义的符号",下面的错误
class MyString{public:typedef char* iterator;typedef const char* const_iterator;iterator begin();iterator end();const_iterator begin() const;const_iterator end() const;//MyString();MyString(const char* str = "");MyString(const MyString& s);~MyString();void swap(MyString& s);MyString& operator=(MyString tmp);char& operator[](size_t pos);const char& operator[](size_t pos) const;size_t capacity() const;size_t size() const;void reserve(size_t n);void resize(size_t n, char ch = '\0');void clear();size_t find(char ch, size_t pos = 0);size_t find(const char* sub, size_t pos = 0);void push_back(char ch);void append(const char* str);void insert(size_t pos, char ch);void insert(size_t pos, const char* str);void erase(size_t pos, size_t len = npos);MyString& operator+=(char ch);MyString& operator+=(const char* str);bool operator<(const MyString& s) const;bool operator==(const MyString& s) const;bool operator<=(const MyString& s) const;bool operator>(const MyString& s) const;bool operator>=(const MyString& s) const;bool operator!=(const MyString& s) const;MyString substr(size_t pos, size_t len = npos);const char* c_str() const;private:char* _str;size_t _size;size_t _capacity;public:const static size_t npos; //初始化必须在源文件内};std::ostream& operator<<(std::ostream& out, const MyString& s);std::istream& operator>>(std::istream& in, MyString& s);
2、缺省值
缺省值应该在 .h 头文件中,不应该在 .cpp 源文件中
如果出现,就会出现如下错误:“MyString::resize”: 重定义默认参数 : 参数 1
void MyString::resize(size_t n, char ch = '\0') //缺省值在头文件的声明中
{if (n <= _size){_str[n] = '\0';_size = n;}else{reserve(n);while (_size < n){_str[_size] = ch;++_size;}_str[_size] = '\0';}
}