I'm making my own string class and I'd like to ensure that CString a = "Hello " + "World!"; works (i.e. does not give a compiler error such as: cannot add 2 pointers).
My string class automatically converts to char* when needed and thus writing printf(a) would not break the code.
Is there any way to replace the compiler behavior around characters ? (i.e. between inverted commas, "abc"). Or, alternatively, to change the behavior of the + operator to handle strings?
You can't do exactly that because you can only overload operators for class types, and a string literal does not have class type.
You can take advantage of the concatenation of string literals that takes place during preprocessing:
CString a = "Hello " "World!";
or you can create a CString temporary and append to it:
CString a = CString("Hello ") + "World!";
or you could have a CString constructor that takes more than one argument:
CString a("Hello ", "World!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With