Friend Function operator overload+

Need help with a friend function that accepts a char* and string from a class and appends them. This is what I put into the function but it returns garbage and then crashes. Any pointers. I can supply with full code from the class if necessary. Thanks

1
2
3
4
5
6
7
8
 String1 operator+(char *bufferString, String1 &stringIn)
{
	String1 temp;
	cout << stringIn;
	cout << bufferString;
	//temp = bufferString + stringIn;
	return temp;
}
Your problem is recursion.

An operator like that would be used like this:
1
2
3
char foo[] ="Hello";
String1 bar("world");
String1 gaz = foo + bar;

A char*, a '+' and a String1.

Now, in your line 6 you have an expression, which has
a char*, a '+' and a String1.

That calls this very same operator+(char*, String1&) function. Within the call is line 6, which calls ...


If the operator is a friend of String1 (nobody wants to befriend char* any more), then it can access the internals of the stringIn and temp objects and can thus implement the "addition".

Another common style is to implement standalone operators by using a compound assignment member operator:
1
2
3
4
5
6
7
8
9
10
11
12
String1 operator+ ( const char * lhs, const String1 & rhs )
{
	String1 temp( lhs ); // assuming there is String1::String1(const char*)
	temp += rhs; // assuming there is String::operator+= (const String1 &)
	return temp;
}

String1 operator+ ( String1 lhs, const char * rhs )
{
	lhs += String1( rhs) ;
	return lhs;
}
I implemented your first function but my compiler throws an error around the += in the temp += rhs? any ideas?
I had to make it temp = temp + string and now at least my program doesnt crash but it doesnt seem to be appending lhs to rhs
Implement String1 & String1::operator+= ( const String1 & ). Then you can use the +=
Topic archived. No new replies allowed.