I am currently reading this topic. The textbook gives an example but cannot function properly. I am using Dev-C++.
It uses the operator +, to make it a tool to combine two strings. For example, if the first word is "Barack ",the second word is "Obama",then using this overloaded operator will make it "Barack Obama".
When I run this,the screen displayed(for one second) "This Application has requested the runtime to terminate it in an unusual way. Please contact the application's support team for more information"
I do not know what happens, anybody help me please
How should I interpret the first and second Str in Str Str::operator+(Str s)?
Is it correct to see the word "Obama" acting as a parameter for operator+ (i.e. the s)?
So where is the first word "Barack " being represented?
Thank you!
The way you're using it, yes, you should see "Obama" acting as the argument and "Barack" is represented by data. You're calling the operator function like this: (s1+s2).show();
You can think of the s1+s2 as being equivalent to: s1.operator+(s2)
This means that when you reference variables directly, without using them by accessing s or tmp, you're using the current object's data members. You could write it like this if it would be clearer:
1 2 3 4 5 6 7 8 9 10 11
Str Str::operator+(Str s)
{
// Make a string as large as the current string plus the new string.
Str tmp(this->len + s.len);
// Put the current string in our temp string.
strcpy(tmp.data, this->data);
// Concatenate on the new string.
strcat(tmp.data, s.data);
// And return our result.
return tmp;
}
So, in your main code example you're calling operator+ from s1, which is equal to "Barack", and sending it s2, which is equal to "Obama". One thing that might work a bit better would be: