954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

STL developers lazy or did I miss something?

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

winbatch
Posting Pro in Training
466 posts since Feb 2005
Reputation Points: 68
Solved Threads: 18
 
string f = "F" + "F";


The last one isoperator+ 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.]

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

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?

winbatch
Posting Pro in Training
466 posts since Feb 2005
Reputation Points: 68
Solved Threads: 18
 

I believe so.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

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

Dogtree
Posting Whiz in Training
233 posts since May 2005
Reputation Points: 35
Solved Threads: 3
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You