String类的C++实现是一个C++面向对象的典型例子。在很多名企面试中,这个类的实现是经常考到的。那么,它的具体实现是如何的呢?
下面就来看看String类是如何实现的:
//String类的声明
class String
{
public:
String(const char *str
= NULL);
String(const String
&other);
~ String(void);
//注意赋值操作符返回的是对象的引用
String & operate
=(const String &other);
private:
char
*m_data;
};
//String类的析构函数,由于不涉及继承关系,所以没用virtual
String::~String(void)
{
delete [] m_data;
}
//String的构造函数
String::String(const char *str)
{
//字符串为空
if(str==NULL)
{
m_data = new char[1];
*m_data = ‘\
}
else
{
int length = strlen(str);
m_data = new char[length+1];
strcpy(m_data, str);
}
}
//拷贝构造函数
String::String(const String &other)
{
int length =
strlen(other.m_data);
m_data = new
char[length+1];
strcpy(m_data,
other.m_data);
}
//赋值运算符
String & String::operate =(const String &other)
{
//防止自我赋值
if(this == &other)
return *this;
//释放原来的内存
delete [] m_data;
//分配新内存,拷贝数据
int length =
strlen(other.m_data);
m_data = new
char[length+1];
strcpy(m_data,
other.m_data);
return *this;
}
Copyright 2011-2020 © MallocFree. All rights reserved.