I am creating my own string class
and I want to make sure that CString A = "Hello" + "World!";
works (i.e. the compiler does not return error such as: can not add 2 points
).
My string class
is automatically converted to char *
and thus printf (a)
The code does not break
is there any way to change the compiler behavior around the character ? (I.e., between the inverted commas, "abc"
). Or, alternatively, to change the behavior of +
operator to control string
Correct answer
No
James McNellis has already answered this question, so I will not extend.
A possible alternative ...
(I use std :: string because I do not have any information on in-house string)
Add any type of typed type in your syntax:
typed std :: string S_; Int main (int argc, char * argv []) {std :: string s = s_ ("hello") + s_ ("world"); Std :: cout & lt; & Lt; "S:" & lt; & Lt; S & lt; & Lt; Std :: endl; Return 0; }
But then, I do not pollute the global name space with a two-letter symbol for a little sugar ... and as far as I know, the code is disabled (Two string objects, plus a temporary, the compiler will optimize it without guarantee ...)
Due to curiosity ...
As a curiosity, the string Wrap a thin square, you can "add" those two points. Firstly, make the cover:
class StringThinWrapper {public: StringThinWrapper (const char * p): m_p (p) {} operator confine * () console {Returns M_P; } Private: const char * const m_p; };
As you can see, it's both inline, and nothing will ... yet, it is capable of putting itself in the const char * indicator (like this The hack is dangerous, so
inline studs :: string operator + (cons string string using & amp; amp; LHS, constant string wap & amp; rhs) {std: : String S (LHS); S + = rhs; Return s;}
And now, let's easily type a main
function using the cover:
< Code> typedef StringThinWrapper S_; Int main (int argc, char * argv []) {std :: string s = s_ ("hello") + s_ ("world"); std :: cout & lt; "S:"
Which gives the following results and gives:
s: Hello World
Disclaimer: I just wanted to play with the idea of your question, and share it with you. Do not apply, because you can. Actually, this code should be used to efficiently use all the cases Should be refined to cover before, and even then, a simple typedef std :: string S_;
will be better IMHO.
AFAIK, I do not use it because I am happy with the current STL API.
And what about C ++ 0x?
In C ++ 0x, you will have a slightly different code capable of making your own literals:
std :: string operator "str" (const char * P) {return std :: string (p); }
and you will use it:
int main (int argc, char * argv []) {std :: string s = "hello" Str + "world" str; Std :: cout & lt; & Lt; "S:" & lt; & Lt; S & lt; & Lt; Std :: endl; Return 0; }
For more information, see the following SO questions: .
Comments
Post a Comment