仿照string类,实现myString
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
using namespace std;
class myString
{
private:
char *str;//记录c风格的字符串
int size = 0; //记录字符串的实际长度
int capacity = 0;//字符串的最大容量
public:
//无参构造
myString();
//有参构造
myString(const char *s);//有参构造 string s("hello wirld");
//判空函数
bool empty();
//返回当前对象分配的存储空间能保存的字符数量
int get_capacity();
//size函数
int get_size();
//c_str函数
char *c_str();
//at函数
char &at(int index);
//push_back
bool push_back(const char ch);
//二倍扩容
void expend();
};
#endif // MYSTRING_H
#include "myString.h"
//无参构造
myString::myString():size(10), capacity(10)
{
str = new char[size];
}
//有参构造
myString::myString(const char *s)//有参构造 string s("hello world");
{
for(int i=0; size = i, s[i] != 0; i++);
str = new char[size+1];
memcpy(str, s, size);
str[size] = '\0';
capacity = size;
}
//判空函数
bool myString::empty()
{
return size == 0;
}
//返回当前对象分配的存储空间能保存的字符数量
int myString::get_capacity()
{
return capacity;
}
//size函数
int myString::get_size()
{
return size;
}
//c_str函数
char *myString::c_str()
{
return str;
}
//at函数
char& myString::at(int index)
{
return str[index];
}
//push_back
bool myString::push_back(const char ch)
{
if(capacity == size)
{
expend();
}
at(size) = ch;
size++;
return true;
}
//二倍扩容
void myString::expend()
{
capacity *= 2;
char *temp = new char[capacity];
memcpy(temp, str, size);
delete []str;
str = temp;
}
#include "myString.h"
int main()
{
myString str("hello");
cout << str.at(2) << endl;
cout << "字符串实际长度为:" << str.get_size() << endl;
cout << "字符串容量为:" << str.get_capacity() << endl;
str.at(0) = 'H';
cout << "str = " << str.c_str() << endl;
str.push_back('A');
cout << "str = " << str.c_str() << endl;
cout << "字符串实际长度为:" << str.get_size() << endl;
cout << "字符串容量为:" << str.get_capacity() << endl;
return 0;
}
思维导图: