10.2 作业
1. 编程
#include <iostream>
#include <string.h>
using namespace std;class MyString
{
private:int size;int capacity;char *str;public:// 构造函数MyString();MyString(const char *);// 拷贝构造MyString(const MyString &);// 赋值运算符MyString &operator=(const MyString &);MyString &operator=(const char *);// 长度int len();// 拼接void strcat(const MyString &other);MyString const operator+(const MyString &) const;// 比较int strcmp(const MyString &);// 输入void in();// 输出void out();// 内存管理~MyString();
};MyString::MyString() : size(0), capacity(128), str(new char[capacity]) { memset(str, 0, capacity); }
MyString::MyString(const char *s) : size(0), capacity(128), str(new char[capacity])
{memset(str, 0, capacity);while (*s != 0 && size < capacity){str[size] = *s;size++;s++;}
}MyString::MyString(const MyString &other) : size(other.size), capacity(other.capacity), str(new char[capacity])
{memset(str, 0, capacity);for (int i = 0; i < size; ++i){str[i] = other.str[i];}
}MyString &MyString::operator=(const MyString &other)
{if (this == &other) return *this;delete []str;size = other.size;capacity = other.capacity;str = new char[capacity];memset(str, 0, capacity);for (int i = 0; i < size; ++i){str[i] = other.str[i];}return *this;
}MyString &MyString::operator=(const char *s)
{size = 0;memset(str, 0, capacity);while (*s != 0 && size < capacity){str[size] = *s;size++;s++;}
}int MyString::len()
{return size;
}void MyString::strcat(const MyString &other)
{int tmp = size + other.size;for (int i = 0; size < tmp && size < capacity; ++size, ++i){str[size] = other.str[i];}
}MyString const MyString::operator+(const MyString &other) const
{MyString ret(*this);ret.strcat(other);return ret;
}int MyString::strcmp(const MyString &other)
{for (int i = 0; i < size && i < other.size; ++i){if (str[i] != other.str[i]){return str[i] - other.str[i];}}if (size == other.size)return 0;else if (size > other.size)return str[other.size];else if (size < other.size)return other.str[size];
}void MyString::in()
{char s[128];cin >> s;size = 0;memset(str, 0, capacity);while (s[size] != 0 && size < capacity){str[size] = s[size];size++;}
}void MyString::out()
{for (int i = 0; i < size; ++i){cout << str[i];}cout << endl;
}MyString::~MyString()
{delete[] str;
}int main()
{//无参构造 MyString s1;s1.out();//有参构造MyString s2("hello");s2.out();//拷贝构造MyString s3(s2);s3.out();//输入s3.in();s3.out();//拷贝赋值s3 = s2;s3.out();//赋值运算符s3 = " world";s3.out();//拼接MyString s4 = s2 + s3;s4.out();//长度cout << s4.len() << endl;//比较s1 = "abc", s2 = "abd";cout << s1.strcmp(s2) << endl;cout << s2.strcmp(s1) << endl;
}
2. 刷题