Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

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

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*?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...