Operator overloading abstract data types is all dandy but is the same thing possible with basic data types. For instance, can I add a custom '+' operator to 'char' or redefine it for 'int'?
Printable View
Operator overloading abstract data types is all dandy but is the same thing possible with basic data types. For instance, can I add a custom '+' operator to 'char' or redefine it for 'int'?
No, as far as I know. In C++, the primitive data types are usually implemented directly, not as classes.
You could, however, use a hack like this:
Why do you want to do that? You could always define your own my_char class that does what you want. Redefining the behaviour of the primitive types would be very confusing.Code:#define int int_class
The answer is yes, but it will take more lines of code than you expect. You create a class with the basic type you are modifying as a private member, and then add all the functionality you want to the class as overloaded functions. Some has almost certainly already done this once, so a search for a template that already implements some basic class would be a good starting point.
So, what does "char + char" do? Once you come up with a name for this operation, write a function with that name that takes two char arguments.
Neither char + char nor char* + char* are invalid. They just don't do what you expect.
Operator overloading was originally meant for extending the existing semantics of operators to new data types. It was certainly not meant to change the semantics for existing data types. (Changing the semantics for new data types happens and can be useful, but must be used with great care.)
That's because operator+ for a pointer is valid only with an integral or enumeration type, not another pointer.
I wonder how much you know about std::string? It already is quite good at concatenating std::strings, char's and char*'s.
For example, if you want to concatenate char*'s and char's, you might do it like this:
Code:char* hello = "Hello";
char* world = "world";
std::string result = std::string(hello) + ' ' + world + '!';
You can get a string's char* by calling it's c_str() method
QuantumPete
>> Strings are fine, except I want it to return a char *.
I think the point was that you should use strings pretty much everywhere.
Note that c_str() returns a const char*, so you can't modify the C style string it returns. If you really do need a char* that can be modified, then you would have to copy the return value of c_str() into your char* with strcpy. Of course, if you're going to do that, you might as well not use strings at all and just do everything the C way and do the concatenation with strcat.
If you want a mutable char*, use a vector<char> and do &v[0].
It is guaranteed to work, as of the 2003 minor revision of the C++ standard.
But ONLY for vector. Not for list or deque or anything else.