如何重载operator ==()为类的指针? [英] How to overload operator==() for a pointer to the class?
问题描述
我有一个类 AString
。这是很基本的:
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.
有一种方法允许比较运算符比较 * AString
与 const char *
Is there a way to allow the comparison operator to compare *AString
with const char*
?
推荐答案
不,没有。
重载 operator ==
,您必须提供一个用户定义的类型作为操作数和指针之一( AString *
或 const char *
)不符合条件。
当比较两个指针时,编译器有足够的内置 operator ==
,因此不会考虑将其中一个参数转换为类类型。
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.
这篇关于如何重载operator ==()为类的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!