一、思维导图
二、完成下面类
代码
#include <cstring>
#include <iostream>using namespace std;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);}// 拷贝构造函数myString(const myString &other){size = other.size;str = new char[size + 1];strcpy(str, other.str);}// 析构函数~myString(){delete[] str; // 释放内存}// 判空函数bool isEmpty() const{return (size == 0);}// size函数返回字符串长度int getSize() const{return size;}// c_str返回C风格字符串const char *c_str() const{return str;}// at函数访问指定位置字符char &at(int pos){if (pos >= 0 && pos < size){return str[pos];}else{// 索引超出范围,返回默认的字符static char default_char = '\0';return default_char;}}
};int main()
{myString str1; // 调用无参构造函数cout << "String 1: " << str1.c_str() << endl;myString str2("Hello Shanghai !"); // 调用有参构造函数cout << "String 2: " << str2.c_str() << endl;myString str3 = str2; // 调用拷贝构造函数cout << "String 3: " << str3.c_str() << endl;cout << "string是否为空? " << (str1.isEmpty() ? "Yes" : "No") << endl;cout << "String2大小: " << str2.getSize() << endl;cout << "String2的第四个位置: " << str2.at(4) << endl;return 0;
}
实现效果