Link to home
Start Free TrialLog in
Avatar of stevehibbert
stevehibbert

asked on

MyString mystring = "This" + "Not Working"; String Class Binary External Operator Overloading Problem

Regarding the classic C++ custom string class:

I am having a problem overloading the binary addition operator, so that I can add two literal strings to make a (for the sake of argument, what I am going to call...) MyString.

Take this example:
    MyString mystring = "This" + "IsNotWorking";

I would expect the order of execution to be...
 - mystring assigned value "This"
 - mystring and "IsNotWorking" added together by overloaded class unary addition operator for adding a MyString object to a literal object.
I have both of these components working, I can assign from a literal, and I can add a MyString to a Literal.

The compiler is throwing "cannot add two pointers", which is fair comment, if the first thing the compiler does is the addition, and not the assignment.  Is there a way around so that I can create an object from the overloaded addition of two constant literals?

ASKER CERTIFIED SOLUTION
Avatar of DanRollins
DanRollins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And BTW, the easiest way to do this with string literals is:
MyString s ="This "  "Is working";   // no operator at all -- string literals are automatically concatenated.

Avatar of stevehibbert
stevehibbert

ASKER

Great tips, thanks for those.  I have been working around this but was, kind of, intellectually interested to see if it was possible to somehow over-ride the binary+ between two pointers to char or wchar_t.  

The easy way, adding two string literals by omitting the operator, is elegant.  

The underlying idea was to be able to build strings in one line ( not that the compiler really cares), as I do a ton of string processing in my code.  I've gone for a home-made string class based on TCHAR type that replicates std::string functions, so I can flip to/from Unicode in Win32 non-MFC stuff.  It's a bit of work but very re-usable stuff.

Many thanks for the feedback, it is greatly appreciated.
Thanks for the points and the grade.
One last thought:
It might be possible to create a custom operator, say +& that would know what to do when encountering two char* strings.  But I've never tried that.
I've never looked into custom operators, it did not occur to me.  Thanks for the pointer, and really appreciate the help.