How to overload operator==() for a pointer to the class?

后端 未结 5 824
北海茫月
北海茫月 2020-12-06 18:06

I have a class called AString. It is pretty basic:

class AString
{
public:
    AString(const char *pSetString = NULL);
    ~AString();
    bool          


        
相关标签:
5条回答
  • 2020-12-06 18:29
     if (myString == "bar")
    

    even if you get it to work, is very confusing for others. You are comparing a pointer to an object with a string literal. A much clearer way to get this working is dereference the pointer, and provide an overload like

    bool operator==(const char* pSetString);
    
    0 讨论(0)
  • 2020-12-06 18:41

    I think what you want is wrong since it obscures the type system of C++. myString is a pointer to a AString and not a AString. Dont't try to hide the fact that it's a pointer. It's an entry point for ugly bugs and if you're coding in a team everyone else would be nothing but confused!

    0 讨论(0)
  • 2020-12-06 18:41

    [ Original answer was wrong and thus corrected below ]

    As pointed out by Oli Charlesworth, in a comment below, this is impossible.

    You would need to define an operator like

       bool operator==(const AString *as, const char *cs); // Note: C++ will not do that
    

    but you cannot overload an operator unless one of its parameters is non-primitive type - and pointers (both pointers to AString and pointers to char) are primitive types.

    0 讨论(0)
  • 2020-12-06 18:54

    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.

    0 讨论(0)
  • 2020-12-06 18:54

    Not unless you wrap it in some sort of smart-pointer class, but that would make the semantics weird. What's wrong with if (*myString == "bar")?

    0 讨论(0)
提交回复
热议问题