昨天在面试迅游的时候被问到如何实现一个String类,由于之前没有做过这种题目(剑指offer中有提到)
所以晚上的时候自己实现了一下,以下附上代码和注释
class StringClass
{
public:
StringClass(); //默认构造函数
StringClass(const StringClass &str); //拷贝构造函数
StringClass(char* str); //通用构造函数
~StringClass(); //析构
int Length(); //获取长度
StringClass& operator+=(const StringClass &rhs); //重载+=运算符
StringClass& operator=(const StringClass &rhs); //重载=运算符
StringClass operator+(const StringClass &rhs); //重载+运算符
friend ostream& operator<<(ostream &os, StringClass &rhs); //重载<<运算符 由于操作对象为OS 不是类本身,所以需要声明为友元函数
// >>运算符同理 这里就不写了
char operator[](const int &index); //获取长度
private:
char *_data;
};
StringClass::StringClass()
:_data(nullptr){
}
StringClass::StringClass(const StringClass &str){
if (&str == this) return; //如果相等不复制
_data = new char[strlen(str._data) + 1];
strcpy(_data, str._data);
}
StringClass::StringClass(char* str){
int length = strlen(str);
_data = new char[length + 1];
strcpy(_data, str);
}
StringClass::~StringClass()
{
delete[] _data; //new[]和delete[]配对
}
StringClass& StringClass::operator+=(const StringClass &rhs){
char *tmp = new char[Length() + strlen(rhs._data) +1];
strcpy(tmp, _data);
strcat(tmp, rhs._data);
delete[] _data;
_data = tmp;
return *this;
}
StringClass& StringClass::operator=(const StringClass &rhs){
if (&rhs != this){
delete[] _data;
_data = new char[strlen(rhs._data) + 1];
strcpy(_data, rhs._data);
}
return *this;
}
StringClass StringClass::operator+(const StringClass &rhs){
StringClass nString;
int L = strlen(rhs._data);
nString._data = new char[Length() + L + 1];
strcpy(nString._data, this->_data);
strcat(nString._data, rhs._data);
return nString;
}
char StringClass::operator[](const int &index){
if (index >= 0 && index <+Length()) return *(_data + index);
}
ostream& operator<<(ostream &os, StringClass &rhs){
os << rhs._data;
return os;
}
int StringClass::Length(){
if (_data == nullptr) return 0;
int L = 0;
while (*(_data+L) != '\0'){
++L;
}
return L;
}
在mian函数中进行测试
StringClass str("abc");
StringClass str1("def");
cout << str << " Length=" << str.Length() << endl; //输出abc Length=3
cout << str + str1<< endl; //输出abcdef
str += str1;
cout << str << " Length=" << str.Length() <<endl; //输出abcdef Length=6
总结:
实际上还有挺多操作没写的 operator还有对于char的操作 以及<<和==操作
写出一个string类中体现了C++很多基础 如内存的控制, 引用,重载,友元等,算得上一个不错的练习
更新: 在看剑指offer时注意到关于operator=函数应该使用另一种解法(思路为使用局部变量的作用域),若采用本文中的delete方法时,可能会出现_data是空指针的情况,导致程序奔溃