#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
public:
//无参构造
My_string(); //默认给32字节
//有参构造
My_string(char* str);
//拷贝构造
My_string(const My_string &other);
//拷贝赋值
My_string &operator=(const My_string &other);
//判空
bool empty();
//返回长度
unsigned long size_str();
//将C++风格转化成C风格
const char *back_str();
//at
char at_str(unsigned int pos);
//指定访问某个字符
char &operator[](unsigned int pos);
//strcat
My_string &operator+(My_string &other);
//strcmp
bool operator>(My_string &other);
//析构函数
~My_string();
private:
char* _str;
unsigned long size;
};
//无参构造
My_string::My_string():size(32) //默认给32字节
{
_str = new char[this->size];
strcpy(_str, "");
}
//有参构造
My_string::My_string(char* str)
{
this->size = strlen(str)+1;
_str = new char[size];
strcpy(_str, str);
}
//拷贝构造
My_string::My_string(const My_string &other):size(other.size)
{
_str = new char[this->size];
strcpy(this->_str, other._str);
}
//拷贝赋值
//函数名之前加作用域!!!!!!!!
My_string &My_string::operator=(const My_string &other)
{
this->size = other.size;
_str = new char[this->size];
strcpy(_str, other._str);
return *this;
}
//判空
bool My_string::empty()
{
return strlen(this->_str) == 0?1 : 0;
}
//返回长度
unsigned long My_string::size_str()
{
return this->size-1;
}
//将C++风格转化成C风格
const char *My_string::back_str()
{
return this->_str;
}
//at
char My_string::at_str(unsigned int pos)
{
if (pos > this->size)
{
cout << "段错误" << endl;
}
return *(this->_str + pos);
}
//指定访问某个字符
char &My_string::operator[](unsigned int pos)
{
if (pos > this->size)
{
cout << "越界" << endl;
}
return *(this->_str+pos);
}
//strcat
My_string &My_string::operator+(My_string &other)
{
if (0 == other.size || 0 == this->size)
{
cout << "error" << endl;
}
char *temp = new char[this->size + other.size - 1]; //两个字符串结尾\0
for (unsigned int i = 0 ; i < this->size-1 ; i++)
{
*(temp+i) = *(this->_str+i);
}
for (unsigned int i = this->size-1 ; i < this->size + other.size - 1 ; i++)
{
*(temp+i) = *(this->_str+i);
}
this->_str = temp;
temp = nullptr;
this->size = this->size + other.size - 1;
return *this;
}
//strcmp >
bool My_string::operator>(My_string &other)
{
unsigned int temp = this->size > other.size ? this->size : other.size;
for (unsigned int i = 0 ; i < temp ; i++)
{
return *(this->_str + i) > *(other._str + i) ? 1 : 0;
}
return 0;
}
//strcmp <
bool My_string::operator>(My_string &other)
{
unsigned int temp = this->size > other.size ? this->size : other.size;
for (unsigned int i = 0 ; i < temp ; i++)
{
return *(this->_str + i) < *(other._str + i) ? 1 : 0;
}
return 0;
}
//析构函数
My_string::~My_string()
{
delete[] _str;
_str = nullptr;
}
int main()
{
return 0;
}