operator overloading

i dont have idea how to use the overloaded '+' operator to concatenate two strings
i wish to recieve a response from anyone who knows it and can explain it in detail
When overloading operators inside of a class, the this pointer is the left hand object and the only parameter is the right hand object:
1
2
3
4
5
6
7
8
9
10
11
12
13
class MyString
{
    //...
public:
    //...
    MyString operator+(const MyString &with) const
    {
        //+ makes a new copy that is a combination of both original without affecting them
        MyString copy (*this); //construct from this one,
        copy.internaldatawhatever; //append to the internal data
        return(copy); return the copy
    }
};

Overloading it as a global operator means you have two parameters, the left and right being the left and right respectively:
1
2
3
4
5
6
MyString operator+(const std::string &L, const MyString &R)
{
    MyString copy (L); //your string class CAN construct itself from a std::string, right?
    copy.internaldatawhatever; //append R to copy
    return(copy);
}


See http://www.cplusplus.com/doc/tutorial/classes2/ for more info.
Last edited on
Also, a note:
It's sometimes easier/shorter to define the '+=' (for strings: 'append') operator first and then define the '+' (for strings: 'concatenate') operator in terms of '+='. Since you often need both, it can safe you some doubling!
There is no default + operator for strings. L B has explained how to make a custom class to do this.

The += operator is possibly what you are looking for. You can use it as in the example below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string>
#include <iostream>
using std::string; using std::cout;

int main()
{
    string A = "Hello";
    string B = "World";

    string C = A;    //String C is now "Hello"
    C += " ";        //String C is now "Hello "
    C += B;          //String C is now "Hello World"

    cout << C;

    return 0;
}
Last edited on
if I were to make an overloaded class I would probably:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyString
{
public:
    MyString(std::string in) : TheString(in) { }
    str() { return TheString; }
    MyString operator+(const MyString &RightSide) const
    {
        std::string temp = TheString;
        temp += RightSide.str();
        MyString out(temp);
        return out;
    }
private:
    std::string TheString;
};


You'd also have to add a few friend functions to overload the << and >> operators for ostream, ofstream, istream and ifstream.
There is a default + operator for std::string + const char * (in std::string class), and const char * + std::string (global operator).
Last edited on
Topic archived. No new replies allowed.