Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. using namespace std;
  5.  
  6. class MyString {
  7.     char *data;
  8.   public:
  9.     MyString() : data(nullptr) {}
  10.     MyString(const MyString &line) {
  11.         data = new char[strlen(line.data)];
  12.         strcpy(data, line.data);
  13.     }
  14.     MyString(const char *line) {
  15.         this->data = new char[strlen(line)];
  16.         strcpy(this->data, line);
  17.     }
  18.     ~MyString() {
  19.         delete[] this->data;
  20.     }
  21.     MyString &operator=(const MyString &line) {
  22.         if (this == &line) {
  23.             return *this;
  24.         }
  25.         delete this->data;
  26.         data = new char[strlen(line.data)];
  27.         strcpy(this->data, line.data);
  28.         return *this;
  29.     }
  30.     MyString operator+(const MyString &that);
  31.     friend istream &operator>>(istream &is, MyString &s);
  32.     friend ostream &operator<<(ostream &os, const MyString &s);
  33.     friend MyString operator+(const char *a, const MyString &s);
  34. };
  35.  
  36. MyString MyString::operator+(const MyString &that) {
  37.     return this->data + that;
  38. }
  39. istream &operator>>(istream &is, MyString &s) {
  40.     is >> s.data;
  41.     return is;
  42. }
  43. ostream &operator<<(ostream &os, const MyString &s) {
  44.     os << s.data;
  45.     return os;
  46. }
  47. MyString operator+(const char *a, const MyString &s) {
  48.     char *line = new char[strlen(a) + strlen(s.data) - 1]{0};
  49.     strcat(strcat(line, a), s.data);
  50.     MyString string(line);
  51.     delete[] line;
  52.     return string;
  53. }
  54.  
  55. int main() {
  56.     MyString s1("Sasha"), s2("Masha"), s3("Dasha");
  57.     cout << s1 << endl;
  58.     cout << s2 << endl;
  59.     cout << s1 + s2 + s3 << endl;
  60.     char s5[] = "pupa";
  61.     MyString s6("lupa");
  62.     MyString s7 = s5 + s6;
  63.     cout << s7 << endl;
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement