Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CString a = "Hello " + "World!"; Is it possible?

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?

like image 954
Sanctus2099 Avatar asked Mar 23 '26 04:03

Sanctus2099


1 Answers

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!");
like image 109
James McNellis Avatar answered Mar 24 '26 16:03

James McNellis