C++面试题:String类的实现

来源:互联网 发布:mac搜索文件命令 编辑:程序博客网 时间:2024/06/03 20:51
#include<iostream>
#include<cstring>
using namespace std;



class String
{
friendostream& operator<<(ostream& os, const String &other);
public:
String(const char *str = NULL);
String(const String& other);
~String();
String& operator=(const String &other);
private:
char *m_cdata;


};


String::~String()
{
delete[]m_cdata;
}


String::String(const char *str)
{
if (str == nullptr)
{
m_cdata = new char[1];
*m_cdata = '\0';
}
else
{
int length = strlen(str);
m_cdata = new char[length + 1];
strcpy_s(m_cdata,length+1, str);
}
}


String::String(const String& other)
{
int length = strlen(other.m_cdata);
m_cdata = new char[length + 1];
strcpy_s(m_cdata, length+1,other.m_cdata);
}


String& String::operator=(const String &other)
{
//检查自己赋值
if (this == &other)
return *this;
//释放点原有的内存
delete[]m_cdata;
//分配新的内存,并且复制内容
int length = strlen(other.m_cdata);
m_cdata = new char[length + 1];
strcpy_s(m_cdata,length+1, other.m_cdata);
return *this;
}
ostream& operator<<(ostream& out,const String &other)
{
out << other.m_cdata;
return out;
}


int main()
{
String str("hello");
const String str2 = str;
cout << str2 << endl;


system("pause");
return 0;


}
原创粉丝点击