侯捷C++(String类)
注意事项(class with pointer members)
Big Three,三个特殊函数:析构函数、拷贝构造函数、拷贝赋值函数。
代码(String类)
#include <iostream>
#include <bits/c++config.h>
#include <string.h>
using namespace std;
class String
{
public:
//构造函数,只有构造函数可以用列表初始化
inline String(const char* cStr = " ") : m_data(new char[strlen(cStr) + 1])
{
strcpy(m_data, cStr);
}
//拷贝构造函数
inline String(const String& otherStr) : m_data(new char[strlen(otherStr.m_data) + 1])
{
strcpy(m_data, otherStr.m_data);
}
//析构函数
inline ~String()
{
delete []m_data;
}
//追加函数
String& append(const String& otherStr);
//得到m_data
inline char* getChar() const { return m_data; }
//拷贝赋值函数
String& operator = (const String& otherStr);
private:
char* m_data;
};
inline String& String::append(const String& otherStr)
{
char *pTmp = new char[strlen(this->m_data) + strlen(otherStr.m_data) +1];
strcpy(pTmp, this->m_data);
strcat(pTmp, otherStr.m_data);
m_data = pTmp;
return *this;
}
inline String& String::operator = (const String& otherStr)
{
//检测自我赋值,否则会删除自己
if (this == &otherStr)
{
return *this;
}
else
{
delete []m_data;
m_data = new char[strlen(otherStr.m_data) + 1];
strcpy(m_data, otherStr.m_data);
return *this;
}
}
inline ostream& operator << (ostream& os, const String& str)
{
return os << str.getChar() << endl;
}
int main()
{
String s1("hello");
cout << "构造函数:" << s1;
String s2(s1);
cout << "拷贝构造函数:" << s2;
String s3 = s2;
cout << "拷贝赋值函数:" << s3;
String s4;
s4.append("hello").append(" world!");
cout << "append函数:" << s4;
return 0;
}