本文最后更新于100 天前,其中的信息可能已经过时,如有错误请发送邮件到big_fw@foxmail.com
#include<iostream>
#include<cstring>
/*
1.串声明
创建
删除
获取长度
串索引
串赋值
串比较
串拷贝
串拼接
串输出
*/
using namespace std;
class MyString{
private:
char* m_string;
size_t size;
public:
//串输出
friend ostream& operator<<(ostream& os,MyString& str);
//默认构造
MyString() : size(0) {
m_string = new char[1];
m_string[0] = '\0';
}
//参数构造
MyString(const char* value) : size(strlen(value)) {
m_string = new char[size+1];
strcpy(m_string,value);
}
//拷贝构造
MyString(MyString& other) : size(other.size) {
m_string = new char[other.size+1];
strcpy(m_string,other.m_string);
}
//移动构造
MyString(MyString&& other) noexcept : size(other.size),m_string(other.m_string){
other.m_string = nullptr;
other.size = 0;
}
//析构
~MyString(){
delete[] m_string;
}
//获取长度
size_t getLength() const;
//串的赋值string a =“”
MyString& operator=(const char* string);
//string a
//string b a=b
MyString& operator=(MyString& string);
MyString& operator=(MyString str);
//串的比较
bool operator==(MyString& str);
bool operator!=(MyString& str);
//串索引
char& operator[](size_t index);
//串拼接
MyString operator+(MyString& str);
};
size_t MyString::getLength() const{
return size;
}
bool MyString::operator==(MyString& str){
return strcmp(m_string,str.m_string) == 0;
}
bool MyString::operator!=(MyString& str){
return strcmp(m_string,str.m_string) != 0;
}
//若干个=重载
MyString& MyString::operator=(const char* string){
if(this->m_string != string){
size_t new_size = strlen(string);
delete[] m_string;
m_string = new char[new_size + 1];
strcpy(m_string,string);
size = strlen(string);
}
return *this;
}
MyString& MyString::operator=(MyString& string){
if(*this != string){
delete[] m_string;
m_string = new char[string.size + 1];
strcpy(m_string,string.m_string);
size = string.size;
}
return *this;
}
MyString& MyString::operator=(MyString string){
if(*this != string){
delete[] m_string;
m_string = new char[string.size + 1];
strcpy(m_string,string.m_string);
size = string.size;
}
return *this;
}
//////////////////////
char& MyString::operator[](size_t index){
return m_string[index];
}
MyString MyString::operator+(MyString& str){
MyString result;
size_t new_size = strlen(m_string) + strlen(str.m_string);
char* new_string = new char[new_size+1];
strcpy(new_string,m_string);
strcat(new_string,str.m_string);
result = new_string;
return new_string;
}
ostream& operator<<(ostream& os,MyString& str){
os << str.m_string;
return os;
}
int main(){
MyString str;//测试默认构造
MyString str1("BISTU");//测试参数构造
str = "ABCD";//测试赋值运算符重载
MyString str2(str); //测试拷贝构造
cout << "str1:" << str1 << endl;
cout << "str:" << str << endl;
cout << "str2:" << str2 << endl;
cout << "str1的长度为:" << str1.getLength() << endl;//测试getlength()
//测试比较运算符重载
if(str1 == str2){
cout << "str1 = str2" << endl;
}else cout << "str1 != str2" << endl;
if(str != str2){
cout << "str != str2" << endl;
}else cout << "str = str2" << endl;
MyString str3(str1 + str);//同时测试移动构造和+重载
cout << str3 << endl;
return 0;
}