“operator==”和“operator==”之间的混淆或“运算符LPCTSTR”

发布于 2024-10-03 12:35:37 字数 396 浏览 5 评论 0原文

我有这么一小段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情仇皆在手 2024-10-10 12:35:37

与需要用户定义转换的运算符 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.

毁虫ゝ 2024-10-10 12:35:37

比较 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文