C++学习笔记总结练习:字符串类实现

基本功能

  1. 实现头文件的封装:MyString.h

  2. 缺省构造函数对字符串的初始化MyString()

  3. 使用构造函数初始化字符串的另外两种方式,动态指针+拷贝构造函数 )

  4. 析构函数,释放动态申请的字符串空间

  5. 重载输出运算符 <<

  6. 重载赋值运算符 =

  7. 重载下标运算符 [],索引输出

拓展功能.

  1. 字符串长度的比较

  2. 字符串的排序功能

  3. 字符串的倒置

  4. 字符串中指定两个字符的交换

  5. 查找某字符串是否位于指定的字符串中(采用暴力查找)

实现

/* 
* C++ string 类的实现
* 1. 构造函数和析构函数
* 2. 字符串长度
* 3. 重载=运算符
* 4. 重载+=运算符
* 5. 重载<< >> 运算符
* 6. 重载比较运算符
* 7. 重载[]下标运算符
*/

#include 
#include 
using namespace std;

class MyString
{
private:
    char * str;
    int length;
public:
    // 长度
    int size ()const {
        return length;
    };
    char* getstr()const{
        return str;
    }
    // 默认构造函数
    MyString();
    // 字符串构造函数
    MyString(const char*);
    // 复制构造函数
    MyString(const MyString& b);

    // 重载等号运算符
    MyString& operator=(const MyString &b);
    // 重载+=运算符
    MyString& operator+=(const MyString &b);
    // 重载比较运算符
    bool operator<(const MyString &b);
    // 重载下标运算符
    char& operator[](const int &index) const ;
    // 重载输入输出操作
    friend ostream& operator<<(ostream& ,const MyString &b);
    ~MyString();
};

MyString::MyString()
{
    str = new char[1];
    str[0]='\0';
    length = 0;
}

MyString::MyString(const char* b){
    if(b){
        length = strlen(b);
        str = new char[length+1];
        strcpy(str,b);
    }
    else{
        MyString();
    }
}
MyString::MyString(const MyString&b){
    length = b.size();
    if(length>0)
    str = new char[length+1];
    else
    MyString();
}

MyString& MyString::operator=(const MyString &b){
    if(&b == this){
        return *this;
    }
    delete[] str;
    length = b.size();
    str = new char[length + 1];
    strcpy(str,b.getstr());
    return *this;
}

MyString& MyString::operator+=(const MyString&b){
    if(b.size()==0){
        return *this;
    }
    char* temp = new char[length+b.length+1];
    strcpy(temp,str);
    strcat(temp,b.getstr());
    delete[] str;
    str = temp;
    return *this;
}

char& MyString::operator[](const int &index)const {
    if(index>length)return str[length];
    return str[index];
}

bool MyString::operator<(const MyString &b){
    for(int i=0;ib.size())return false;
        if(b[i]>str[i])return true;
        if(b[i]

你可能感兴趣的:(c++,c语言,嵌入式软件,c++,学习,笔记)