C++ string overloaded for "operator+"

http://www.cplusplus.com/reference/string/string/

I was looking at the above reference, and it does not mention overloading the addition operator (operator+). I did a little experimentation with the program below, and notice that without including <string> I can do some basic operations as listed in the above reference including operator=, but I cannot use operator+ or << unless I include <string>. Is string partially defined in <iostream> and then has more advanced methods defined in <string> ??? Why would it be split up like that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
//#include <string>

using namespace std;

int main() {

	string str1 = "this is a string ", str2 = "another string ";
	printf("%s \n", str1.c_str());
	str1.append(str2);
	printf("%s \n", str1.c_str());

	//without <string>: 'std::string' does not define this operator
	//str1 = str1 + str2;
	//without <string>: no operator found which takes a right-hand operand of type 'std::string'
	//cout << str1 << endl; 
	return 0;
}


1
2
str1 = str1 + str2;
cout << str1 << endl; 

Both compile just fine for me, regardless of whether <string> is included if <iostream> is present.

std::string::operator+() and std::string::operator<<() are documented here:
http://www.cplusplus.com/reference/string/operator+/
http://www.cplusplus.com/reference/string/operator%3C%3C/
Last edited on
Thanks Helios.

I tried it in MinGW without <string> and it does compile fine there. But not in VC++ 2008, unless I include <string>. I assume you're not using Visual Studio, VC++ ???
My test above was indeed done using MinGW.
VC++ does complains about the overloaded operators when <string> is not included.

The simplest rule is "always include the headers that go with the class you're using". What other headers each header includes is not defined by the standard, AFAIK, so each compiler vendor is free to do it however they please.
Topic archived. No new replies allowed.