目录
一、【string】实现框架
string.h
Test.cpp
二、函数接口
1.成员函数
①获取成员变量
②默认成员函数
1)构造函数
···含参构造
···无参构造
2)拷贝构造函数
···传统写法
···现代写法
3)析构函数
③遍历功能实现
1) operator[ ] 重载
2) 迭代器
④比较运算符重载函数
⑤容量相关
1) reserve()
2) resize()
⑥增删查改
1) 增添
push_back()
append()
insert()
---指定位置插入单个字符
---指定位置插入字符串
2) 删除
---erase()
---clear()
3)查找
find()
---find单个字符
---find字符串
substr
⑦+=运算符重载函数
⑧赋值运算符重载
1) 传统写法
2) 现代写法
2.非成员函数
1) 流插入运算符重载函数
2) 流提取运算符重载函数
三、代码汇总
String.h
Test.cpp
通过上一篇博客【string】基本用法 的学习,我们已经对string相关接口设计和实现有了较为全面和深入的了解,本篇博客将深入讲解重要的一些接口底层是如何实现的,知其然更要知其所以然~
string.h头文件中是整个string的模拟实现,而Test.cpp中写了main函数,调用string.h中的测试函数,需要的头文件都包含在了Test.cpp中,下面讲解具体函数接口的时候就只展示 string.h 头文件中的内容了~
namespace dck //为了防止和库中的string冲突,我们将自定义实现的string封装在dck中
{
class string
{
public:
//各个成员函数
private:
char* _str; //指向动态开辟的空间
int _size; //有效字符个数
int _capacity; //字符串容量
};
//非成员函数
void test_string()
{
//测试各个函数接口实现的正确性
}
}
#define _CRT_SECURE_NO_WARNINGS
#include
using namespace std;
#include"string.h"
int main()
{
dck::test_string();
}
二、函数接口
实现具体的某个函数接口时,简洁起见,我们只给出实现该函数接口需要用到的其它函数接口~
namespace dck
{
class string
{
public:
//获取成员变量
char* c_str()
{
return _str;
}
int size()
{
return _size;
}
int capacity()
{
return _capacity;
}
private:
char* _str;
int _size;
int _capacity;
};
}
namespace dck
{
class string
{
public:
//含参构造
string(const char* str = "") //缺省参数给常量字符串,常量字符串中默认含有'\0'
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1]; //实际开空间是 容量 + 1('\0')
strcpy(_str, str);
}
private:
char* _str;
int _size;
int _capacity;
};
}
namespace dck
{
class string
{
public:
//无参构造
string()
:_str(new char[1]) //开几个空间都行
, _size(0)
, _capacity(0)
{
_str[0] = '\0';
}
private:
char* _str;
int _size;
int _capacity;
};
}
此处为了测试相关功能,需要用到遍历,下面有详细介绍~
#include
namespace dck
{
class string
{
public:
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//默认构造
string(const char* str = "")
:_size(strlen(str))
,_capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
//拷贝构造传统写法
string(const string& s)
{
_str = new char[s._capacity + 1];
strcpy(_str, s._str);
_size = s._size;
_capacity = s._capacity;
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello world"; //构造
string s2 = s1; //拷贝构造
for (size_t i = 0;i < s2.size();i++)
{
cout << s2[i] << " "; //h e l l o w o r l d
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//含参构造
string(const char* str = "")
:_size(strlen(str))
,_capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
//拷贝构造现代写法
string(const string& s)
{
string tmp(s._str); //调用含参构造函数初始化创建tmp
//此时调用的swap函数是标准库string中的全局函数
swap(_str, tmp._str);
swap(_size, tmp._size);
swap(_capacity, tmp._capacity);
//tmp是局部变量,出了作用域之后自动销毁,不需要我们手动释放空间
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello world"; //构造
string s2 = s1; //拷贝构造
for (size_t i = 0;i < s2.size();i++)
{
cout << s2[i] << " "; //h e l l o w o r l d
}
cout << endl;
}
}
后面要实现的赋值运算符重载函数现代写法也会用到交换函数,我们不妨将其实现成成员函数
#include
namespace dck
{
class string
{
public:
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
//拷贝构造现代写法
//自定义交换函数的实现
void swap(string& s)
{
//调用库中的swap函数
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
string(const string& s)
//有些编译器下不会对this指向的对象进行初始化,因此调用swap和tmp交换完之后调用析构函数可能会崩溃
:_str(nullptr)
,_size(0)
,_capacity(0)
{
string tmp(s._str); //构造函数创建tmp对象
swap(tmp); //调用自定义swap函数
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello world"; //构造
string s2 = s1; //拷贝构造
for (size_t i = 0;i < s2.size();i++)
{
cout << s2[i] << " "; //h e l l o w o r l d
}
cout << endl;
}
}
namespace dck
{
class string
{
public:
//析构函数
~string()
{
delete[] _str;
_str = nullptr;
_size = _capacity = 0;
}
private:
char* _str;
int _size;
int _capacity;
};
}
#include
namespace dck
{
class string
{
public:
//operator[]重载
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//含参构造
string(const char* str = "") //缺省参数给常量字符串,常量字符串中默认含有'\0'
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1]; //实际开空间是 容量 + 1('\0')
strcpy(_str, str);
}
//获取有效字符个数
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
//测试逻辑
void test_string()
{
string s = "hello world";
for (size_t i = 0;i < s.size(); i++)
{
cout << s[i] << " "; //h e l l o w o r l d
}
cout << endl;
}
}
namespace dck
{
class string
{
public:
//读&&写
typedef char* iterator;
//读
typedef const char* const_iterator;
char* begin()
{
return _str;
}
const char* begin() const
{
return _str;
}
char* end()
{
return _str + _size;
}
const char* end()const
{
return _str + _size;
}
//含参构造
string(const char* str = "") //缺省参数给常量字符串,常量字符串中默认含有'\0'
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1]; //实际开空间是 容量 + 1('\0')
strcpy(_str, str);
}
private:
char* _str;
int _size;
int _capacity;
};
//只读
void test_string1()
{
string s1 = "hello world";
string::iterator it = s1.begin();
while (it != s1.end())
{
cout << *it << " "; //h e l l o w o r l d
it++;
}
cout << endl;
}
//读&&写
void test_string2()
{
string s2 = "hello world";
string::iterator it = s2.begin();
while (it != s2.end())
{
*it = 'x';
cout << *it << " "; //x x x x x x x x x x x
it++;
}
cout << endl;
}
}
namespace dck
{
class string
{
public:
bool operator>(const string& s)const
{
return strcmp(_str, s._str) > 0;
}
bool operator==(const string& s)const
{
return strcmp(_str, s._str) == 0;
}
bool operator>=(const string& s)const
{
return *this > s || *this == s;
}
bool operator != (const string& s)const
{
return !(*this == s);
}
bool operator < (const string& s)const
{
return !(*this >= s);
}
bool operator <= (const string& s)const
{
return !(*this > s);
}
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello world";
string s2 = "hello dck";
cout << (s1 > s2) << endl; //1
cout << (s1 == s2) << endl; //0
cout << (s1 >= s2) << endl; //1
cout << (s1 != s2) << endl; //1
cout << (s1 < s2) << endl; //0
cout << (s1 <= s2) << endl; //0
}
}
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
//n > _capacity 使用reserve才有意义
if (n > _capacity)
{
//模拟realloc异地扩容机制
char* tmp = new char[n + 1]; //开辟一段新空间
strcpy(tmp, _str); //拷贝旧空间数据到新空间
delete[] _str; //释放旧空间
_str = tmp; //_str指向新空间
_capacity = n; //更新_capacity
}
}
//获取容量
int capacity()
{
return _capacity;
}
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello world";
cout << s1.capacity() << endl; //11
s1.reserve(100);
cout << s1.capacity() << endl; //100
}
}
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[_capacity + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
void resize(size_t n, char ch = '\0')
{
//当 n <= _size 相当于删除元素
if (n <= _size)
{
_str[n] = '\0';
_size = n;
}
//当 n > _size 相当于插入元素
else
{
reserve(n);
while(_size < n)
{
_str[_size] = ch;
_size++;
}
_str[_size] = '\0';
}
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//获取容量
int capacity()
{
return _capacity;
}
//获取有效字符个数
int size()
{
return _size;
}
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello world";
s1.resize(20, 'x');
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //最终结果:h e l l o w o r l d x x x x x x x x x
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
//尾插
void push_back(char ch)
{
//判断是否需要扩容
if (_size == _capacity)
{
//为0时给4个空间大小, 不为0时一次扩两倍
reserve(_capacity == 0? 4 : _capacity * 2);
}
_str[_size] = ch;
_size++;
_str[_size] = '\0';
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//默认构造函数
string(const char* str = "")
:_size(strlen(str))
,_capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "";
s1.push_back('1');
s1.push_back('2');
s1.push_back('3');
s1.push_back('4');
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //1 2 3 4
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
//追加字符串
void append(const char* str)
{
//判断是否需要扩容
size_t len = strlen(str);
if (_size + len > _capacity)
{
reserve(_size + len);
}
strcpy(_str + _size, str);
_size += len;
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//默认构造函数
string(const char* str = "")
:_size(strlen(str))
,_capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello ";
s1.append("world");
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //h e l l o w o r l d
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
//指定位置插入单个字符
void insert(size_t pos, char ch)
{
assert(pos <= _size);
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
size_t end = _size + 1;
while (end > pos)
{
_str[end] = _str[end - 1];
--end;
}
_str[pos] = ch;
_size++;
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//默认构造函数
string(const char* str = "")
:_size(strlen(str))
,_capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello";
s1.insert(0, '#');
s1.insert(3, '*');
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //# h e * l l o
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
//指定位置插入字符串
void insert(size_t pos, const char* str)
{
assert(pos <= _size);
size_t len = strlen(str);
while(_size + len > _capacity)
{
reserve(_size + len);
}
int end = _size + len;
while (end > pos)
{
_str[end] = _str[end - len];
--end;
}
strncpy(_str + pos, str, len);
_size += len;
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//默认构造函数
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello";
s1.insert(2, "xxxx");
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //h e x x x x l l o
}
cout << endl;
string s2 = "hello";
s2.insert(0, "****");
for (size_t i = 0;i < s2.size();i++)
{
cout << s2[i] << " "; //* * * * h e l l o
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
//删除指定位置
void erase(size_t pos, size_t len = npos) //模拟库中的实现,长度默认给无符号的整数-1(很大的数字)
{
assert(pos < _size);
if(len == npos || pos + len >= _size) //从pos位置开始删完
{
_str[pos] = '\0';
_size = pos;
}
else
{
int begin = pos + len;
while (begin <= _size)
{
_str[begin - len] = _str[begin];
++begin;
}
_size -= len;
}
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//默认构造函数
string(const char* str = "")
:_size(strlen(str))
,_capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
//默认npos是-1
const static size_t npos = -1;
};
void test_string()
{
string s1 = "hello world";
s1.erase(2, 5);
for(size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //h e o r l d
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
void clear()
{
_str[0] = '\0';
_size = 0;
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
void test_string()
{
string s1 = "hello world";
cout << s1.size() << endl; //11
s1.clear();
cout << s1.size() << endl; //0
}
}
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
//查找指定字符,返回下标
size_t find(char ch, size_t pos = 0)
{
for (size_t i = 0;i < _size;i++)
{
if (_str[i] == ch)
{
return i;
}
}
return npos;
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//默认构造函数
string(const char* str)
:_size(strlen(str))
,_capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
//默认npos是-1
const static size_t npos = -1;
};
void test_string()
{
string s1 = "hello world";
size_t pos = s1.find('o'); //4
cout << pos << endl;
}
}
#include
namespace dck
{
class string
{
public:
//查找指定字符,返回下标
size_t find(const char* sub, size_t pos = 0)
{
//调用strstr函数
const char* p = strstr(_str + pos, sub); //strstr返回的是子串在主串中首次出现的位置(指针),找不到返回空
if (p)
{
return p - _str; //指针相减得到的是两个指针之间的字符个数
}
else
{
return npos;
}
}
//默认构造函数
string(const char* str)
:_size(strlen(str))
,_capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
private:
char* _str;
int _size;
int _capacity;
//默认npos是-1
const static size_t npos = -1;
};
void test_string()
{
string s1 = "hello world";
size_t i = s1.find("wor");
cout << i << endl; //6
size_t j = s1.find("wol");
cout << j << endl; //很大的数字(size_t -1)
}
}
增删查都有了,似乎还没有改,而其实改就是在查的基础上直接重新赋值就行~
这里要用到+=操作,下一个函数接口就会实现~
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[_capacity + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
void push_back(char ch)
{
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
_str[_size] = ch;
++_size;
_str[_size] = '\0';
}
//+=
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
//取子串
string substr(size_t pos, size_t len = npos)
{
string s;
size_t end = pos + len;
if (len == npos || pos + len > _size) //有多少,取多少
{
len = _size - pos;
end = _size;
}
s.reserve(len);
for (size_t i = pos;i < end;i++)
{
s += _str[i];
}
return s;
}
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
const static size_t npos = -1;
};
void test_string()
{
string s1 = "hello world";
string s2 = s1.substr(2, 3);
for (size_t i = 0;i < s2.size();i++)
{
cout << s2[i] << " "; //l l o
}
cout << endl;
string s3 = s1.substr(3);
for (size_t i = 0;i < s3.size();i++)
{
cout << s3[i] << " "; //l o w o r l d
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[_capacity + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
void push_back(char ch)
{
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
_str[_size] = ch;
++_size;
_str[_size] = '\0';
}
void append(const char* str)
{
size_t len = strlen(str);
if (_size + len > _capacity)
{
reserve(_size + len);
}
strcpy(_str + _size, str);
_size += len;
}
//+=字符
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
//+=字符串
string& operator+=(const char* str)
{
append(str);
return *this;
}
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
const static size_t npos = -1;
};
void test_string()
{
string s1 = "hello ";
s1 += 'x';
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //h e l l o x
}
cout << endl;
string s2 = "hello ";
s2 += "world";
for (size_t i = 0;i < s2.size();i++)
{
cout << s2[i] << " "; //h e l l o w o r l d
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
//赋值传统写法
string& operator=(const string& s)
{
if (this != &s) //避免自己给自己赋值
{
char* tmp = new char[s._capacity + 1]; //重新开辟一块和s大小一样的空间,避免空间浪费
strcpy(tmp, s._str);
delete[] _str;
_str = tmp;
_size = s._size;
_capacity = s._capacity;
}
return *this;
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//默认构造函数
string(const char* str)
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
//默认npos是-1
const static size_t npos = -1;
};
void test_string()
{
string s1 = "hello world";
string s2 = "xxxxxxxxx";
s1 = s2; //赋值
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //x x x x x x x x x
}
cout << endl;
}
}
#include
namespace dck
{
class string
{
public:
//赋值重载现代写法
//自定义交换函数的实现
void swap(string& s)
{
//调用库中的swap函数
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
string& operator=(const string& s)
{
if (this != &s) //避免自己给自己赋值
{
string tmp(s._str);
swap(tmp);
}
return *this;
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//含参构造函数
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
//默认npos是-1
const static size_t npos = -1;
};
void test_string()
{
string s1 = "hello world";
string s2 = "xxxxxxxxx";
s1 = s2; //赋值
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //x x x x x x x x x
}
cout << endl;
}
}
其实还有一种更加巧妙的写法,既然要在赋值重载函数内部创建局部对象tmp,为何不直接用传值传参呢?
#include
namespace dck
{
class string
{
public:
//赋值重载现代写法
//自定义交换函数的实现
void swap(string& s)
{
//调用库中的swap函数
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
string& operator=(string tmp) //传值传参自动调用拷贝构造函数
{
swap(tmp);
return *this;
}
//运算符重载函数
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//含参构造函数
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
//拷贝构造
string(const string& s)
:_str(nullptr)
, _size(0)
, _capacity(0)
{
string tmp(s._str);
swap(tmp);
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
//默认npos是-1
const static size_t npos = -1;
};
void test_string()
{
string s1 = "hello world";
string s2 = "xxxxxxxxx";
s1 = s2; //赋值
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i] << " "; //x x x x x x x x x
}
cout << endl;
}
}
为啥不把流插入和流提取重载成为成员函数,我在【类和对象】日期类总结 已经详细介绍过了,而不需要和日期类一样用到友元是因为我们不需要访问类的私有成员变量~
#include
namespace dck
{
class string
{
public:
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
int size()
{
return _size;
}
private:
char* _str;
int _size;
int _capacity;
};
//流插入运算符
ostream& operator<<(ostream& out, string& s)
{
for (size_t i = 0; i < s.size();i++)
{
out << s[i];
}
return out;
}
void test_string()
{
string s1 = "hello world";
cout << s1 << endl; //hello world
}
}
在 【string】基本用法 一文最后中已经介绍了cin输入的特点(默认以空格或者换行作为输入内容的分割,导致cin无法读入回车或者换行),因此下面这种实现会导致无法停止输入
所以我们调用了istream库中的get函数,一个个读取字符,遇到回车才结束
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
void push_back(char ch)
{
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
_str[_size] = ch;
_size++;
_str[_size] = '\0';
}
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
int size()
{
return _size;
}
void clear()
{
_str[0] = '\0';
_size = 0;
}
private:
char* _str;
int _size;
int _capacity;
};
//流插入运算符
ostream& operator<<(ostream& out, string& s)
{
for (size_t i = 0; i < s.size();i++)
{
out << s[i];
}
return out;
}
//流提取运算符
istream& operator>>(istream& in, string& s)
{
s.clear(); //输入前清空数据
char ch;
ch = in.get(); //类似于C语言的getchar(),get()遇到回车才会停止读取
while (ch != ' ' && ch != '\n')
{
s += ch;
ch = in.get();
}
return in;
}
void test_string()
{
string s1;
cin >> s1;
cout << s1;
}
}
但是上面的代码实现有个小瑕疵,就是可能会频繁扩容,因此我们可以提前用reserve开空间,但是问题是我们如果只输出了很少的数据,又会造成空间浪费,而下面这种实现方法既避免了频繁扩容,又不会造成太多的空间浪费
#include
namespace dck
{
class string
{
public:
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
void append(const char* str)
{
size_t len = strlen(str);
if (len + _size == _capacity)
{
reserve(len + _size);
}
strcpy(_str + _size, str);
_size += len;
}
string& operator+=(const char* str)
{
append(str);
return *this;
}
//含参构造
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
int size()
{
return _size;
}
void clear()
{
_str[0] = '\0';
_size = 0;
}
private:
char* _str;
int _size;
int _capacity;
};
//流插入运算符
ostream& operator<<(ostream& out, string& s)
{
for (size_t i = 0; i < s.size();i++)
{
out << s[i];
}
return out;
}
//流提取运算符
istream& operator>>(istream& in, string& s)
{
s.clear(); //输入前清空数据
char buff[129]; //定义一个能存放129个char类型大小(包含'\0')的数组---具体多大无所谓
size_t i = 0;
char ch;
ch = in.get(); //类似于C语言的getchar(),get()遇到回车才会停止读取
while (ch != ' ' && ch != '\n')
{
buff[i++] = ch; //将要输入的字符暂且放入buff数组中
//buff数组满了,就+=到s上
if (i == 128)
{
buff[i] = '\0';
s += buff;
i = 0;
}
ch = in.get();
}
if (i != 0) //i != 0说明某一次循环中buff数组还没放满就遇到了空格或是换行
{
buff[i] = '\0';
s += buff;
}
return in;
}
void test_string1()
{
string s1;
cin >> s1; //hello world
cout << s1;//hello
}
void test_string2()
{
string s1;
string s2;
cin >> s1 >> s2; //hello world
cout << s1 << endl << s2; //hello
//world
}
}
三、代码汇总
#include
namespace dck
{
class string
{
public:
//①获取成员变量
char* c_str()
{
return _str;
}
int size()
{
return _size;
}
int capacity()
{
return _capacity;
}
//②默认成员函数
//含参构造
string(const char* str = "") //缺省参数给常量字符串,常量字符串中默认含有'\0'
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1]; //实际开空间是 容量 + 1('\0')
strcpy(_str, str);
}
//拷贝构造现代写法
void swap(string& s)
{
//调用库中的swap函数
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
string(const string& s)
:_str(nullptr)
, _size(0)
, _capacity(0)
{
string tmp(s._str);
swap(tmp);
}
//析构函数
~string()
{
delete[] _str;
_str = nullptr;
_size = _capacity = 0;
}
//③遍历实现
//operator[]重载
char operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
//迭代器
typedef char* iterator;
typedef const char* const_iterator;
char* begin()
{
return _str;
}
const char* begin() const
{
return _str;
}
char* end()
{
return _str + _size;
}
const char* end()const
{
return _str + _size;
}
//④比较运算符重载
bool operator>(const string& s)const
{
return strcmp(_str, s._str) > 0;
}
bool operator==(const string& s)const
{
return strcmp(_str, s._str) == 0;
}
bool operator>=(const string& s)const
{
return *this > s || *this == s;
}
bool operator != (const string& s)const
{
return !(*this == s);
}
bool operator < (const string& s)const
{
return !(*this >= s);
}
bool operator <= (const string& s)const
{
return !(*this > s);
}
//⑤容量相关
//开空间
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
//调整容器大小
void resize(size_t n, char ch = '\0')
{
if (n <= _size)
{
_str[n] = '\0';
_size = n;
}
else
{
reserve(n);
while (_size < n)
{
_str[_size] = ch;
_size++;
}
_str[_size] = '\0';
}
}
//⑥增删查改
//增添
//push_back()
void push_back(char ch)
{
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
_str[_size] = ch;
_size++;
_str[_size] = '\0';
}
//append()
void append(const char* str)
{
//判断是否需要扩容
size_t len = strlen(str);
if (_size + len > _capacity)
{
reserve(_size + len);
}
strcpy(_str + _size, str);
_size += len;
}
//insert()
//插入字符
void insert(size_t pos, char ch)
{
assert(pos <= _size);
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
size_t end = _size + 1;
while (end > pos)
{
_str[end] = _str[end - 1];
--end;
}
_str[pos] = ch;
_size++;
}
//插入字符串
void insert(size_t pos, const char* str)
{
assert(pos <= _size);
size_t len = strlen(str);
while (_size + len > _capacity)
{
reserve(_size + len);
}
int end = _size + len;
while (end > pos)
{
_str[end] = _str[end - len];
--end;
}
strncpy(_str + pos, str, len);
_size += len;
}
//删除
//erase()
void erase(size_t pos, size_t len = npos)
{
assert(pos < _size);
if (len == npos || pos + len >= _size)
{
_str[pos] = '\0';
_size = pos;
}
else
{
int begin = pos + len;
while (begin <= _size)
{
_str[begin - len] = _str[begin];
++begin;
}
_size -= len;
}
}
//clear()
void clear()
{
_str[0] = '\0';
_size = 0;
}
//查找
//查找单个字符
size_t find(char ch, size_t pos = 0)
{
for (size_t i = 0;i < _size;i++)
{
if (_str[i] == ch)
{
return i;
}
}
return npos;
}
//查找字符串
size_t find(const char* sub, size_t pos = 0)
{
const char* p = strstr(_str + pos, sub);
if (p)
{
return p - _str;
}
else
{
return npos;
}
}
//获取子串
string substr(size_t pos, size_t len = npos)
{
string s;
size_t end = pos + len;
if (len == npos || pos + len > _size) //有多少,取多少
{
len = _size - pos;
end = _size;
}
s.reserve(len);
for (size_t i = pos;i < end;i++)
{
s += _str[i];
}
return s;
}
//⑦+=运算符重载
//+=字符
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
//+=字符串
string& operator+=(const char* str)
{
append(str);
return *this;
}
//⑧赋值运算符重载
string& operator=(string tmp)
{
swap(tmp);
return *this;
}
private:
char* _str;
int _size;
int _capacity;
public:
const static size_t npos = -1;
};
//流插入运算符重载
ostream& operator<<(ostream& out, string& s)
{
for (size_t i = 0; i < s.size();i++)
{
out << s[i];
}
return out;
}
//流提取运算符重载
istream& operator>>(istream& in, string& s)
{
s.clear();
char ch;
ch = in.get();
while (ch != ' ' && ch != '\n')
{
s += ch;
ch = in.get();
}
return in;
}
//测试逻辑
//测试默认成员函数
void test_string1()
{
string s1 = "hello world"; //构造函数
string s2 = s1; //拷贝构造
cout << s2 << endl; //hello world
}
//测试遍历
void test_string2()
{
//operator[]重载
string s1 = "hello world";
for (size_t i = 0;i < s1.size();i++)
{
cout << s1[i];//hello world
}
cout << endl;
//迭代器
string s2 = "hello world";
string::iterator it = s2.begin();
while (it != s2.end())
{
cout << *it; //hello world
it++;
}
cout << endl;
}
//测试比较运算符重载函数
void test_string3()
{
string s1 = "hello world";
string s2 = "hello life";
cout << (s1 > s2) << endl; //1
cout << (s1 == s2) << endl; //0
cout << (s1 >= s2) << endl; //1
cout << (s1 != s2) << endl; //1
cout << (s1 < s2) << endl; //0
cout << (s1 <= s2) << endl; //0
}
//测试容量相关
void test_string4()
{
//reserve
string s1 = "hello world";
cout << s1.capacity() << endl; //11
s1.reserve(30);
cout << s1.capacity() << endl; //30
//resize()
string s2 = "hello world";
s2.resize(20, 'x');
cout << s2 << endl; //hello worldxxxxxxxxx
}
//测试增删查改
void test_string5()
{
//push_back
string s1 = "hello ";
s1.push_back('x');
cout << s1 << endl; //hello x
//append
string s2 = "hello ";
s2.append("world");
cout << s2 << endl; //hello world
//insert
string s3 = "hello world";
s3.insert(2, '@');
cout << s3 << endl; //he@llo world
string s4 = "hello world";
s4.insert(2, "xxxxx");
cout << s4 << endl; //hexxxxxllo world
//erase
string s5 = "hello world";
s5.erase(2, 5);
cout << s5 << endl; //heorld
//clear
string s6 = "hello world";
s6.clear();
cout << s6.size() << endl; //0
//find
string s7 = "hello world";
size_t i = s7.find('w', 2);
cout << i << endl; //6
string s8 = "hello world";
size_t j = s8.find("wor", 2);
cout << j << endl; //6
}
//测试+=
void test_string6()
{
string s1 = "hello ";
s1 += 'x';
cout << s1 << endl; //hello x
string s2 = "hello ";
s2 += "world";
cout << s2 << endl; //hello world
}
//测试赋值运算符重载
void test_string7()
{
string s1 = "hello world";
string s2 = "hello life";
s1 = s2;
cout << s1 << endl; //hello life
}
//测试流插入与流提取
void test_string8()
{
string s1;
cin >> s1; //hello world
cout << s1; //hello
}
}
#define _CRT_SECURE_NO_WARNINGS
#include
using namespace std;
#include"string.h"
int main()
{
dck::test_string1();
dck::test_string2();
dck::test_string3();
dck::test_string4();
dck::test_string5();
dck::test_string6();
dck::test_string7();
dck::test_string8();
}