string a = "A";
string b = "B";
string c = a + b;
string d = "D" + a;
string e = a + "D";
string f = "F" + "F";

Why is the last line not something the string class can handle if it can handle cases a, d, and e?
line 73: Error: The operation "const char* + const char*" is illegal.

(Also, is this something that I could add myself? By developing another + operator for string?)

13 Years
Discussion Span
Last Post by Dogtree
string f = "F" + "F";

The last one is operator+ for const char *, like it says, not for strings. You would be trying to overload a builtin, not the string. [Or something to this affect, I believe. The operation on the right happens before the assignment.]


I got you now - it's not even under the 'string' class developers as it would be the char * operator that has to be modified not the string. (So I guess to answer my own question, 'yes, I missed something')

So if I want to do something like that, would require:

string f = "F";



>> So I guess to answer my own question, 'yes, I missed something'
Yes, but it's an easy mistake to make. Since string literals are of type const char *, and it's not possible to overload built-in data types, "F" + "F" is trying to add two addresses, which is an ambiguous, and thus, illegal, operation.

>> correct?
That would work, but a somewhat more concise method is:

std::string("F") + "F"


"F" + std::string("F");

since the + operator allows the string object on either side of the expression.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.