头文件
cpp
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
char* str;
int size;
public:
//无参构造
myString();
//有参构造
myString(const char* s);
//拷贝构造
myString(const myString& other);
//析构函数
~myString();
//拷贝赋值函数
myString& operator=(const myString& other);
//判空
bool empty()const;
//size函数
int getSize()const;
//c_str函数
const char* c_str()const;
//at函数
char &at(int pos);
//加号运算符重载
myString operator+(const myString& other)const;
//加等于运算符重载
myString& operator+=(const myString& other);
//关系运算符>重载
bool operator>(const myString& other)const;
//中括号运算符重载
char& operator[](int pos);
};
#endif // MYSTRING_H
功能文件
cpp
#include "head.h"
//无参构造
myString::myString() :size(10)
{
str = new char[10];
strcpy(str, "");
}
//有参构造
myString::myString(const char* s)
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
}
//拷贝构造
myString::myString(const myString& other)
{
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
}
//析构函数
myString::~myString()
{
delete[] str;
}
//拷贝赋值
myString& myString::operator=(const myString& other)
{
if (this != &other)
{
delete[] str;
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
}
return *this;
}
//判空
bool myString::empty() const
{
return size==0;
}
//size函数
int myString::getSize() const
{
return size;
}
//c_str函数
const char* myString::c_str() const
{
return str;
}
//at函数
char& myString::at(int pos)
{
if (pos >= 0 && pos < size)
{
return str[pos];
}
else
{
cout << "所给位置不合法" << endl;
return str[0];
}
}
//加号运算符重载
myString myString::operator+(const myString& other) const
{
myString temp;
temp.size = this->size + other.size;
temp.str = new char[temp.size + 1];
strcpy(temp.str, this->str);
strcat(temp.str, other.str);
return temp;
}
//加等于运算符重载
myString& myString::operator+=(const myString& other)
{
char* temp = new char[size + other.size + 1];
strcpy(temp, str);
strcat(temp, str);
delete[] str;
str = temp;
size += other.size;
}
//关系运算符>重载
bool myString::operator>(const myString& other) const
{
return strcmp(str, other.str)>0;
}
//中括号运算符重载
char& myString::operator[](int pos)
{
return at(pos);
}
测试文件
cpp
#include "head.h"
int main()
{
myString s1("Hello");
myString s2("World");
// 使用各种函数和运算符
myString s3 = s1 + " " + s2;
cout << s3.c_str() << endl;
s1 += " C++";
cout << s1.c_str() << endl;
if (s1 > s2)
{
cout << s1.c_str() << " is greater than " << s2.c_str() << endl;
return 0;
}
}