Introduction to Iterators
#include <string.h>
#include <iostream>
β
class MyString {
public:
MyString(const char *p = nullptr) {
if (p != nullptr) {
_pstr = new char[strlen(p) + 1];
strcpy(_pstr, p);
} else {
_pstr = new char[1];
*_pstr = '\0';
}
}
β
~MyString() {
delete _pstr;
_pstr = nullptr;
}
β
MyString(const MyString &other) {
_pstr = new char[strlen(other._pstr) + 1];
strcpy(_pstr, other._pstr);
}
β
MyString &operator=(const MyString &other) {
if (this == &other) return *this;
delete[] _pstr;
_pstr = new char[strlen(other._pstr) + 1];
strcpy(_pstr, other._pstr);
return *this;
}
β
bool operator>(const MyString &other) const {
return strcmp(_pstr, other._pstr) > 0;
}
β
bool operator<(const MyString &other) const {
return strcmp(_pstr, other._pstr) < 0;
}
β
bool operator==(const MyString &other) const {
return strcmp(_pstr, other._pstr) == 0;
}
β
int length() const { return strlen(_pstr); }
β
char &operator[](int index) { return _pstr[index]; }
β
const char &operator[](int index) const { return _pstr[index]; }
β
const char *c_str() const { return _pstr; }
β
private:
char *_pstr;
friend std::ostream &operator<<(std::ostream &out, const MyString s);
friend MyString operator+(const MyString &s1, const MyString &s2);
};
β
MyString operator+(const MyString &s1, const MyString &s2) {
MyString tmp;
tmp._pstr = new char[strlen(s1._pstr) + strlen(s2._pstr) + 1];
strcpy(tmp._pstr, s1._pstr);
strcat(tmp._pstr, s2._pstr);
return s;
}
β
std::ostream &operator<<(std::ostream &out, const MyString s) {
return out << s._pstr;
}Last updated