Mira2706

class String

May 29th, 2020
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. //String.h
  2. #ifndef STRING_H
  3. #define STRING_H
  4. #include <iostream>
  5. #include <cstring>
  6.  
  7. class String
  8. {
  9. public:
  10.     String();
  11.     String(const char *s);
  12.     String operator+(String other);
  13.     String& operator=(const String& other);
  14.     bool operator==(String other);
  15.     const char* getStr()const;
  16.     ~String();
  17.  
  18. private:
  19.     char* str;
  20. };
  21. std::ostream& operator<<(std::ostream& os, String other);
  22. #endif // STRING_H
  23.  
  24.  
  25.  
  26. //String.cpp
  27. #include "String.h"
  28.  
  29. String::String()
  30. {}
  31. String::String(const char *s)
  32. {
  33.     str = new char[strlen(s)+1];
  34.     strcpy(str, s);
  35. }
  36.  
  37. String String::operator+(String other)
  38. {
  39.     String result;
  40.     result.str = new char[strlen(str)+strlen(other.str)+1];
  41.     strcpy(result.str, str);
  42.     strcat(result.str, other.str);
  43.     return result;
  44. }
  45. String& String::operator=(const String& other)
  46. {
  47.     delete[] str;
  48.     str = new char(strlen(other.str)+1);
  49.     strcpy(str, other.str);
  50.     return *this;
  51. }
  52.  
  53. bool String::operator==(String other)
  54. {
  55.     if(strcmp(str, other.str) == 0)
  56.         return true;
  57.     else
  58.         return false;
  59. }
  60. const char* String::getStr()const
  61. {
  62.     return str;
  63. }
  64.  
  65.  
  66. String::~String()
  67. {
  68.     delete[] str;
  69. }
  70. std::ostream& operator<<(std::ostream& os, String other)
  71. {
  72.     os << other.getStr();
  73.     return os;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment