thespeedracer38

String Class + Operator Overloading

Feb 17th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cstring>
  4. #include <cstdio>
  5.  
  6. using namespace std;
  7.  
  8. class String{
  9.     char *str;
  10.     int size;
  11.     public:
  12.         String(const char* = "");
  13.         ~String();
  14.         int length();
  15.         bool operator >(String&);
  16.         bool operator <(String&);
  17.         bool operator ==(String&);
  18.         String operator +(const String&);
  19.         friend istream& operator >>(istream&, String&);
  20.         friend ostream& operator <<(ostream&, String&);
  21. };
  22.  
  23. inline String String::operator+(const String &obj){
  24.     int len_1 = size;
  25.     int len_2 = obj.size;
  26.     int concat_len = len_1 + len_2 + 1;
  27.     char *temp = new char[concat_len];
  28.     strcpy(temp, str);
  29.     strcat(temp,obj.str);
  30.     String concat(temp);
  31.     delete[] temp;
  32.     return concat;
  33. }
  34.  
  35. inline String::String(const char *str){
  36.     String::str = new char[strlen(str) + 1];
  37.     strcpy(String::str, str);
  38.     size = strlen(str);
  39. }
  40.  
  41. inline String::~String(){
  42.     delete[] str;
  43.     str = NULL;
  44. }
  45.  
  46. inline int String::length(){
  47.     return size;
  48. }
  49.  
  50. inline bool String::operator >(String &obj){
  51.     return strcmp(str, obj.str) > 0;
  52. }
  53.  
  54. inline bool String::operator <(String &obj){
  55.     return strcmp(str, obj.str) < 0;
  56. }
  57.  
  58. inline bool String::operator ==(String &obj){
  59.     return strcmp(str, obj.str) == 0;
  60. }
  61.  
  62. istream& operator >>(istream &in, String &obj){
  63.     /* Try to do this in the constructor */
  64.     char temp[1024];
  65.     in.getline(temp, 1024);
  66.     delete[] obj.str;
  67.     obj.str = new char[strlen(temp) + 1];
  68.     strcpy(obj.str, temp);
  69.     obj.size = strlen(obj.str);
  70.     return in;
  71. }
  72.  
  73. ostream& operator <<(ostream &out, String &obj){
  74.     out << obj.str;
  75.     return out;
  76. }
  77.  
  78. int main() {
  79.     system("cls");
  80.     cout << "Enter the first string: ";
  81.     String str1;
  82.     cin >> str1;
  83.     cout << "Enter the second string: ";
  84.     String str2;
  85.     cin >> str2;
  86.     String str3 = str1 + String(" ") + str2;
  87.     cout << str3;
  88.     cin.get();
  89.     return 0;
  90. }
Add Comment
Please, Sign In to add comment