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?)

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";
f+="F";

correct?

I believe so.

>> 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"

or

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.