实现目标:
String s1="Hello"
String s2="World""
String s3=s1 + s2
cout<<s3
控制台显示hello world
查了好多资料,照着别人的文档实现了一遍。便于理解自己再记录一下:
实现string类是基于字符数组的,因此需要导入必要的包cstring,cstring是C标准库头文件<string.h>的C++标准库版本,包含了C风格字符串(即’\0’结尾字符串)相关的一些类型和函数的声明。需要输出字符串,因此导入必要的包iostream
先把main函数写出来,如下所示:
#include<cstring>
#include<iostream>
int main() {
string s1 = "hello ";
string s2 = "world";
string s3 = s1 + s2;
std::cout<<s3<<std::endl;
}
现在开始正式实现string类
-
在 C++ 中,语句
string s1 = "hello ";
这种形式的初始化被称为拷贝初始化(copy initialization),它会调用string
类的构造函数来直接构造一个新的string
对象。该构造函数接受一个const char*
参数来创建一个新的string
对象。class string { char* _str; size_t _size; size_t _capacity; public: string():_str(nullptr), _size(0), _capacity(0) {} // 无参构造函数 string(const char* val) { // 有参构造函数 _size = strlen(val); _capacity = _size + 1; _str = new char[_capacity]; strcpy(_str, val); } ~string() { delete[] _str; } };
到这里,main函数的前两条语句已经可以编译通过了。
-
string s3 = s1 + s2;
,这里涉及到两个字符串的拼接,用的是+,因此需要对+进行运算符重载string operator+(const string& other) { size_t new_size = _size + other._size; size_t new_capacity = new_size + 1; char* new_str = new char[new_capacity]; strcpy(new_str, _str); strcat(new_str, other._str); string new_string; new_string._str = new_str; new_string._size = new_size; new_string._capacity = new_capacity; return new_string; }
到这里,main函数的前三条语句已经可以编译通过了。
-
std::cout<<s3<<std::endl;
,这里要重载左移运算符。friend std::ostream& operator<<(std::ostream& stream, const string& source) { if(source._str) { stream << source._str; } return stream; }
好了,已经可以实现题目的要求了。
参考资料: