“operator==”和“operator==”之间的混淆或“运算符LPCTSTR”
我有这么一小段代码:
CString temp = _T("Temp");
if(_T("Temp") == temp)
{
....
}
现在,由于 CString
类中有一个 friend opeartor==
函数,因此 operator==
正在获取调用。但还为 CString
定义了一个运算符 LPCTSTR
。所以我的问题是为什么不使用这个运算符而不是 operator==
?如果我们假设没有friend运算符==
,那么会使用operator LPCTSTR
吗?语言规则对本案有何规定?
I have this small piece of code:
CString temp = _T("Temp");
if(_T("Temp") == temp)
{
....
}
Now, here since there is a friend opeartor==
function in CString
class the operator==
is getting invoked. But there is also a operator LPCTSTR
defined for CString
. So my question is why this operator is not used instead of operator==
? If for a moment if we assume there is no friend operator==
then will operator LPCTSTR
will be used? what does the language rules say about this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与需要用户定义转换的运算符 LPCTSTR 相比,调用重载运算符 == 是完全匹配的。精确匹配优于用户定义的转换。
是的,如果operator==不存在,那么下一个最佳候选者(当然也是可行的)是operator LPCTSTR,它将被调用以获得兼容的参数。
Calling the overloaded operator== is an exact match, compared to operator LPCTSTR which requires a user defined conversion. An exact match is preferred over a user defined conversion.
Yes, if operator== is not there, then the next best candidate (and of course viable) is operator LPCTSTR which will be called for compatible arguments.
比较 LPCTSTR 值对您没有任何好处...比较将检查指针,并告诉您它们是否是相同的地址,这不是(我认为)您想要做的。因此,在没有运算符 == 的情况下,您正在比较指针,也就是说,您会原谅双关语,毫无意义。
对于运算符 ==,有三个版本,一个版本的两个操作数都是 CString,一个版本的第一个操作数是 CString,第三个版本的第二个操作数是 CString。
如果您获取 CString 变量并将其发送到需要 LPCTSTR 的函数(例如 OutputDebugString 等),则将使用运算符 LPCTSTR。
Comparing LPCTSTR values will do you no good at all... the comparison will check the pointers, and give you whether or not they are the same address, which is not (I take it) what you want to do. So, in the absence of operator ==, you are comparing pointers, which is, you'll pardon the pun, pointless.
In the case of operator ==, there are three versions, one with both operands being CString, one with the first operand being CString, and the third with the second operand being CString.
The operator LPCTSTR will be used if you take the CString variable and send it to a function needing an LPCTSTR, like OutputDebugString or something.