仿照string类,实现myString
代码:
/*******************************************/
文件名:mystring.h
/*******************************************/
#include<cstring>
class MyString
{
private:
char *str;
int size;
public:
//无参构造
MyString():size(10)
{
str=new char[size];
str[0] = '\0';
}
MyString(const char *s)
{
int lenth=strlen(s);
str=new char[lenth];
strcpy(str,s);
}
//判空函数
bool empty()const;
//size函数
int c_size()const;
//c_str函数
const char *c_str();
//at
char &at(int index);
//二倍扩容
bool resize();
};
#endif // MYSTRING_H
/*******************************************/
文件名:mystring.cpp
/*******************************************/
#include"mystring.h"
//判空函数
bool MyString::empty()const
{
if(size==0)
{
return 1;
}
return 0;
}
//size函数
int MyString::c_size()const
{
return size;
}
//c_str函数
const char *MyString::c_str()
{
return str;
}
//at
char &MyString::at(int index)
{
return str[index];
}
//二倍扩容
bool MyString::resize()
{
size*=2;
char *temp=new char[size];
strcpy(temp,str);
delete[]str;
str=temp;
return 1;
}
/*******************************************/
文件名:work3.cpp
/*******************************************/
#include"mystring.h"
using namespace std;
int main()
{
MyString s;
MyString s2("hello world!");
const char *c=s2.c_str();
cout<<c<<endl;
cout<<s2.at(2)<<endl;
cout<<s.c_size()<<endl;
s.resize();
cout<<s.c_size()<<endl;
return 0;
}