实现string类
创建一个string类通常会在面试中出现,一个string类通常会有头文件:string.h 主函数文件:main.cpp string文件:string.cpp。
Mystring.h:
#pragma once
#include<iostream>
using namespace std;
class MyString {
private:
char* data;//字符串的首地址
int size;//字符串的长度,不算'\0'
public:
friend ostream& operator<<(ostream& o, MyString s);
MyString();//默认构造
MyString(int n, char c);//构造了n个字符c的字符串
MyString(const char* source);//利用const char* 构造
MyString(const MyString& other);//拷贝构造
~MyString();
char operator[](int i);
char operator[](int i)const;
MyString& operator = (MyString& other);
bool operator == (MyString& other);
MyString& operator+=(const MyString& other);
bool operator>(const MyString& other);
};
Main.cpp:
#include"Mystring.h"
int main() {
MyString s(1, 'c');
return 0;
}
Mystring.cpp:
#include"Mystring.h"
ostream& operator<<(ostream& o, MyString s) {//输出
for (int i = 0; i < s.size; i++) {
o << s[i];
}
return o;
}
MyString::MyString() {//无参构造
size = 0;
data = new char[1];
*data = '\0';
}
MyString::MyString(int n, char c) {//创建一个长度为n的Mystring类型的对象
size = n;
data = new char[n + 1];
char* temp = data;
while (n--) {
*temp++ = c;
}
*temp = '\0';
}
MyString::MyString(const char* source) {//用一个char类型的对象创建一个和source相同的Mystring类型的对象
if (source == nullptr){
size = 0;
data = new char[1];
*data = '\0';
}
else {
size = strlen(source);
data = new char[size + 1];
strcpy_s(data, size + 1, source);
}
}
MyString::MyString(const MyString& other) {//用一个Mystring类型的对象创建一个和source相同的Mystring类型的对象 拷贝构造
size = other.size;
data = new char[size + 1];
strcpy_s(data, size + 1, other.data);
}
MyString::~MyString() {//析构
cout << "--------析构函数---------" << endl;
if (data != nullptr) {
delete[]data;
data = NULL;
size = 0;
}
}
char MyString::operator[](int i) {//下表访问 非常量 可修改
return this->data[i];
}
char MyString::operator[](int i)const {//下表访问 常量 只读 不可修改
return this->data[i];
}
MyString& MyString::operator = (MyString& other) {//赋值
cout << "-------调用了赋值运算符-------" << endl;
if (data != nullptr)delete[] data;
if (other == *this)return *this;
size = other.size;
data = new char[size + 1];
strcpy_s(data, size + 1, other.data);
return *this;
}
bool MyString::operator == (MyString& other) {//判断是否相等
if (other.size != size)return false;
char* p = other.data;
char* q = data;
while (*q && *p) {
if (*p != *q)return false;
q++;
p++;
}
return true;
}
MyString& MyString::operator+=(const MyString& other) {//连接 this 和 other
if (other.size == 0)return *this;
int len = size + other.size;
char* temp = data;
data = new char[len + 1];
strcpy_s(data, size + 1, temp);
strcat_s(data, len + 1, other.data);
delete[] temp;
size = len;
return *this;
}
bool MyString::operator>(const MyString& other) {//判断大小:第一个不同的字符
int i = 0;
while (other.data[i] == data[i] && data[i] != '\0' && other[i] != '\0') {
i++;
}
return data[i] > other.data[i]?true : false;
}
在此基础上还可以进行拓展其他操作。实现string类主要用到的就是上一节讲到的运算符重载。