Search code examples
c++overloadingreturn-value

Why do I get an error when I overload the << on the object returned by the + operator overloaded function


class String
{
    char* array;
public:
    String(const char* s)
    {
        array = new char[strlen(s) + 1]{ '\0' };
        strcpy(array, s);
    }
    ~String()
    {
        if (array)
        {
            delete[]array;
        }
    }
    String operator+ (const char* p)   //返回对象
    {
        String temp(p);
        char* tempStr = temp.array;
        temp.array = new char[strlen(array) + strlen(tempStr) + 1]{ '\0' };
        strcpy(temp.array, array);
        strcat(temp.array, p);
        delete[]tempStr;
        return temp;
    }
    friend ostream& operator<<(ostream& output, String& x);   // <<函数重载只能定义成友元
};

ostream& operator << (ostream& output, String& x)  //对<<重载的方式
{
    output << x.array;
    return output;
}

int main()
{
    String string1("mystring");
    cout << string1 + "ab" << endl;
    cout << string1 << endl;
    return 0;
}

This is my first time asking a question here, so please forgive me if there are any bad descriptions :)

Back to the point ,I have overloaded + and << operators,so I want to get the output "mystringab" by cout<<string1+"ab"<<endl,but the output is garbled.

I think there may be a problem with the + operator overloaded function,can someone please tell me where is the problem?

And if I want to get the correct result, how should I rewrite the overloaded function?


Solution

  • The problem is that the second parameter to overloaded operator<< cannot be bound to an String rvalue since the second parameter is an lvalue reference to a non-const String.

    how should I rewrite the overloaded function?

    You need to make the second parameter to overloaded operator<< a const String& so that it can work with the second argument "ab" as well, as shown below:

    //---------------------------------------- vvvvv------------>low-level const added here
    friend ostream& operator<<(ostream& output,const String& x);
    

    Similarly do the same in the definition:

    //----------------------------------- vvvvv------------>low-level const added here
    ostream& operator << (ostream& output,const String& x) 
    {
        output << x.array;
        return output;
    }
    

    Also, make sure that your program don't have any undefined behavior. For example, by making sure that you use delete or delete[] only when it is safe to do so(that data to which the pointer points is no longer needed). You can use tools such as valgrind to detect some basic problems.