您的位置:首页 > 编程语言 > C语言/C++

自定义的字符串类

2015-11-03 11:08 459 查看
class CTextClass
{

public:

CTextClass(char *pText)
{
Copy(pText);
}

~CTextClass()
{
Delete();
}

CTextClass(const CTextClass &text)
{
Copy(text.m_pText);
}

CTextClass& operator= (const CTextClass &text)
{
if (&text == this)
return *this;

// 需要先删除
Delete();
Copy(text.m_pText);

return *this;
}

char& operator[] (const int index)
{
if (index >= m_length)
throw std::bad_exception();

return m_pText[index];
}

// 需要返回常量否则仍旧可以修改成员变量的值
const char& operator[] (const int index) const
{
if (index >= m_length)
throw std::bad_exception();

return m_pText[index];
}

friend std::ostream& operator << (std::ostream &os, const CTextClass &text);

private:

void Copy(char *pText)
{
m_length = strlen(pText) + 1;
if (m_length == 0)
{
m_length = 1;
m_pText = new char[m_length];
}
else
{
m_pText = new char[m_length + 1];
strcpy(m_pText, pText);
}

m_pText[m_length - 1] = 0;
}

void Delete()
{
if (m_pText)
delete m_pText;

m_pText = nullptr;
m_length = 0;
}

// 禁止使用C++11的转移语法
CTextClass(CTextClass &&text);
CTextClass& operator= (CTextClass &&text);

private:

char* m_pText;
size_t m_length;

};

// 输出test中的内容
std::ostream& operator << (std::ostream &os, const CTextClass &text)
{
return os << text.m_pText << std::endl;
}


需要注意:

1. operator= 重载需要注意判断是否是自己赋值给自己,如果不是自己赋值给自己,需要先将之前的删除掉

2. 常成员函数operator[] 返回值需要是常引用,如果不是就仍旧可以通过 text[0] = 'a'; 来修改成员变量的值

3. 非常成员函数operator[] 返回值需要是引用,需要可以进行赋值操作,否则编译器会报错,需要可以执行text[0] = 'a';的操作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++