I have a class called AString
. It is pretty basic:
class AString
{
public:
AString(const char *pSetString = NULL);
~AString();
bool operator==(const AString &pSetString);
...
protected:
char *pData;
int iDataSize;
}
Now I want to write code like this:
AString *myString = new AString("foo");
if (myString == "bar") {
/* and so on... */
}
However, the existing comparison operator only supports
if (*myString == "bar")
If I omit that asterisk, the compiler is unhappy.
Is there a way to allow the comparison operator to compare *AString
with const char*
?
Functions can be overloaded depending on whether the parameter type is an interior pointer or a native pointer.
Class Member Access Operator (->) Overloading in C++ It is defined to give a class type a "pointer-like" behavior. The operator -> must be a member function. If used, its return type must be a pointer or an object of a class to which you can apply.
In case of operator overloading all parameters must be of the different type than the class or struct that declares the operator. Method overloading is used to create several methods with the same name that performs similar tasks on similar data types.
You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions.
No, there is not.
To overload operator==
, you must provide a user-defined type as one of the operands and a pointer (either AString*
or const char*
) does not qualify.
And when comparing two pointers, the compiler has a very adequate built-in operator==
, so it will not consider converting one of the arguments to a class type.
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