top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Overload string operator + in C++?

+1 vote
263 views

I'am trying to make my own "String" class. But I have problems with overloading operator+. I made operator += that works good and friend operator+ that sometimes does not work as I plan.

String()
{
    length = 0;
    p = new char[1];
    p[0] = '\0';
}
String(const char*s)   
 String()
    {
        length = 0;
        p = new char[1];
        p[0] = '\0';
    }

    String(const char*s)
    {
        length = strlen(s);
        p = new char[length+1];
        strcpy(p, s);
    }

    String(const String& s)
    {
        if (this != &s)
        {
            length = s.length;
            p = new char[s.length + 1];
            strcpy(p, s.p);
        }
    }

    ~String()
    {
        delete[]p;
    };

    String &operator+=(const String&s1)
    {
        String temp;
        temp.length = length + s1.length;
        delete[]temp.p;
        temp.p = new char[temp.length + 1];
        strcpy(temp.p, p);
        strcat(temp.p, s1.p);
        length = temp.length;
        delete[]p;
        p = new char[length + 1];
        strcpy(p, temp.p);
        return *this;
    }

    friend String operator+(const String &s1, const String &s2) 
    {
        String temp1(s1);
        temp1 += s2;
        return temp1;
    }
posted May 1, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
String operator+=(const String&s1)
{
    int temp_length = length + s1.length;
    String temp(*this);
    length = temp_length;
    delete[]p;
    p = new char[length + 1];
    strcpy(p, temp.p);
    strcat(p, s1.p); //<-- This is the problem
    return *this;
}

friend String operator+(const String &s1, const String &s2) 
{
    String temp1(s1);
    temp1 += s1;
    return temp1;
}
answer May 1, 2016 by Rajan Paswan
Similar Questions
+3 votes

Here is working code on gcc compiler but I dont know the name of the symbol "--> ."

#include <stdio.h>
int main()
{
    int x = 10;
    while (x --> 0) // x goes to 0
    {
        printf("%d ", x);
    }
}
...