作业要求,用c语法,实现string类的部分功能
> class myString
{
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
//无参构造
myString():size(10)
{
str = new char[size]; //构造出一个长度为10的字符串
strcpy(str,"");
}
//有参构造
myString(const char *s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str, s);
}
//拷贝构造
//析构函数
//判空函数
//size函数
//c_str函数
//at函数
char &at(int pos)
};
#include <iostream>
#include <string.h>
using namespace std;
class mystring // 自定义string类
{
private:
char *str; // char* c语言风格的的字符串类型
size_t size; // 字符串所占字节大小
public:
mystring(); // 无参构造函数
mystring(const char *s); // 有参构造函数
mystring(const mystring &other); // 拷贝构造函数
~mystring(); // 析构函数
size_t mysize(); // mysize函数类似于size函数
const char *myc_stc(); // 转换为c风格的字符串
char *my_at(int pos, char c);
};
mystring::mystring() : size(32) // 无参构造函数,默认申请32字节长度
{
str = new char[size];
cout << "调用了无参构造函数" << endl;
}
mystring::mystring(const char *s) : size(32) // 有参构造函数,默认申请32字节长度
{
int len = strlen(s) + 1;
str = new char[len];
cout << "调用了有参构造函数" << endl;
}
mystring::~mystring() // 析构函数
{
delete[] str; // 释放str所占用的空间
str = nullptr; // 将str指向空指针
cout << "调用了析构函数" << endl;
}
mystring::mystring(const mystring &other) : size(other.size) // 拷贝构造函数,构造函数后加冒号是初始化表达式
{
str = new char[size];
strcpy(str, other.str);
}
size_t mystring::mysize() // 返回字符串长度
{
return this->size;
}
const char *mystring::myc_stc()
{
return this->str;
}
char *mystring::my_at(int pos, char c)
{
if (pos <= 0 || pos > (int)strlen(str))
{
cout << "input pos-sub error..." << endl; // 输出越界的提示
}
else
{
str[pos] = c;
return str;
}
}
int main()
{
return 0;
}