overloaded '+' operator concatenates strings : Plus « Overload « C++






overloaded '+' operator concatenates strings

  
#include <iostream>
using namespace std;
#include <string.h>
#include <stdlib.h>

class String{
   private:
      enum { SZ=80 };
      char str[SZ];
   public:
      String() { strcpy(str, ""); }
      String( char s[] ) { strcpy(str, s); }
      void display() const { cout << str; }
      String operator + (String ss) const {
         String temp;
         if( strlen(str) + strlen(ss.str) < SZ ){
            strcpy(temp.str, str);
            strcat(temp.str, ss.str);
         }else{
            cout << "\nString overflow"; exit(1);
         }
         return temp;
      }
};
int main(){
   String s1 = "aaa ";
   String s2 = "bbb";
   String s3;

   s1.display();
   s2.display();
   s3.display();

   s3 = s1 + s2;

   s3.display();
   return 0;
}
  
    
  








Related examples in the same category

1.Overload the + relative to MyClass.Overload the + relative to MyClass.
2.Overload + for 'ob + int' as well as 'ob + ob'.Overload + for 'ob + int' as well as 'ob + ob'.
3.String class with custom +/- operator
4.additional meanings for the + and = operations
5.overload the "+" operator so that several angles, in the format degrees minutes seconds, can be added directly.
6.Friendly operator+
7.overloaded '+' operator adds two Distances
8.+ is overloaded for three_d + three_d and for three_d + int.
9.Define operator +(plus) and cast to double operator
10.Overloading the + (or any other binary operator) using a friend allows a built-in type to occur on the left or right side of the operator.
11.friend overloaded + operator