Appearance
模仿 C++ 内置的
<string>,用 C++ 的 class 封装 C 字符串
cpp
#ifndef __MY_STRING_H__
#define __MY_STRING_H__
class MyString {
private:
char *_str;
int _size;
public:
MyString();
MyString(const char *s);
MyString(const MyString &other);
~MyString();
MyString &operator=(const MyString &ohter);
bool empty();
long long int size();
char *c_str();
char &at(int pos);
};
#endifcpp
#include "MyString.h"
#include <cstring>
/**
* 无参构造函数
*/
MyString::MyString() : _size(10) {
this->_str = new char[_size];
strcpy(_str, "");
}
/**
* 有参构造函数
*/
MyString::MyString(const char *s) {
this->_size = strlen(s);
this->_str = new char[_size + 1];
strcpy(_str, s);
}
/**
* 拷贝构造函数
*/
MyString::MyString(const MyString &other) {
this->_str = new char[other._size];
strcpy(this->_str, other._str);
}
/**
* 析构函数
*/
MyString::~MyString() { delete this->_str; }
/**
* 判断空
*/
bool MyString::empty() { return this->size() == 0; }
/**
* 获取长度
*/
long long int MyString::size() { return strlen(this->_str); }
/**
* 获取 C 字符串
*/
char *MyString::c_str() { return this->_str; }
/**
* 获取下标字符
*/
char &MyString::at(int pos) {
if (pos < 0 || pos > this->_size) {
return this->_str[0];
}
return this->_str[pos];
}
/**
* 拷贝赋值函数
*/
MyString &MyString::operator=(const MyString &other) {
if (this != &other) {
this->_size = other._size;
strcpy(this->_str, other._str);
}
return *this;
}cpp
#include "MyString.h"
#include <iostream>
using namespace std;
int main() {
MyString s1; // 无参构造
cout << s1.empty() << endl; // 判断空
s1 = "hello world"; // 拷贝赋值函数
cout << s1.c_str() << endl; // c_str() 函数
cout << s1.size() << endl; // size() 函数
s1.at(5) = 'm'; // at() 函数
cout << s1.c_str() << endl; //
MyString s2(s1); // 拷贝构造函数
cout << s2.c_str() << endl; //
MyString s3 = "dlrow olleh"; // 拷贝构造函数
cout << s3.c_str() << endl; //
s2 = s3; // 拷贝赋值函数
cout << s2.c_str() << endl; //
return 0;
}