string concat

Jun 19, 2014 at 2:10pm
I need to write a program in cpp using operator overloading which can do this for me

'cat' + 'rain' -> will give 'craarin' (it will merge the letters one after the other and add up the extra letter toward the end)

instead of regular string concat

'cat' + 'rain' -> catrain


Is there a way of doing this anyway..
Jun 19, 2014 at 2:46pm
do you need help on the operator overloading syntax or the logic to produce the resultant string?
Jun 19, 2014 at 3:48pm

Should it not be "craatin" ?

Looks like you will need a loop from 0 to the count of the longest input word and append the char at index of each iteration from each input word until you reach the end of both words. So, on the index 3 you will have exhausted the input from "cat" and will be left with 'n' from "rain" to process.

You should now be able to solve your problem.
Jun 19, 2014 at 4:10pm
i basically need help on the operator overloading syntax.. i know the logic i need to use.. i have used operator overloading before but this seems complicated. if u can just start the overload function for me tat will be great
Jun 19, 2014 at 4:27pm

1
2
3
4
5
6
7
8
class MyClass
{
public:
   MyClass();
   virtual ~MyClass();

   MyClass& operator + (const MyClass&);
};


1
2
3
4
5
6
...
MyClass& MyClass::operator+(const MyClass& rhs)
{
    // to do
    return *this;
}
Last edited on Jun 19, 2014 at 4:29pm
Jun 19, 2014 at 7:18pm
operator+ should not modify the object it is invoked on.

1
2
3
4
5
6
7
8
class MyClass
{
public:
   MyClass();
   virtual ~MyClass();

   MyClass operator + (const MyClass&) const;
};


1
2
3
4
5
6
7
...
MyClass MyClass::operator+(const MyClass& rhs) const
{
    MyClass result ;
    // to do
    return result;
}


Last edited on Jun 19, 2014 at 7:18pm
Topic archived. No new replies allowed.