为什么 *&x 与 x 不一样?
简短版本:
以下代码无法编译:
CComBSTR temp;
CMenu().GetMenuString(0, temp, 0);
但是可以编译:
CComBSTR temp;
CMenu().GetMenuString(0, *&temp, 0);
为什么?
完整代码:
#include <atlbase.h>
extern CComModule _Module;
#include <atlapp.h>
#include <atlwin.h>
#include <atlctrls.h>
int main() {
CComBSTR temp;
CMenu().GetMenuString(0, *&temp, 0);
}
GetMenuString
签名(来自 atluser.h
,来自 WTL):
BOOL GetMenuString(UINT nIDItem, BSTR& bstrText, UINT nFlags) const;
Short version:
The following code doesn't compile:
CComBSTR temp;
CMenu().GetMenuString(0, temp, 0);
but this does:
CComBSTR temp;
CMenu().GetMenuString(0, *&temp, 0);
Why?
Full code:
#include <atlbase.h>
extern CComModule _Module;
#include <atlapp.h>
#include <atlwin.h>
#include <atlctrls.h>
int main() {
CComBSTR temp;
CMenu().GetMenuString(0, *&temp, 0);
}
GetMenuString
signature (from atluser.h
, from WTL):
BOOL GetMenuString(UINT nIDItem, BSTR& bstrText, UINT nFlags) const;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为一元运算符
&
和*
可以重载,我猜CComBSTR
会重载。* 更新:*
对于那些想知道如何获取类型已重载
operator&
的变量的地址的人,可以参考 TR1 的std::addressof
,以及它的 Boost 实现以实现 C++03 兼容性。Because the unary operators
&
and*
can be overloaded, which I guessCComBSTR
does.* Update: *
For those who wonder how to get the address of a variable whose type has overloaded
operator&
there is TR1'sstd::addressof
, and a Boost implementation of it for C++03 compatibility.CComBSTR
可能已重载operator *
或operator &
以返回与GetMenuString()< 接收的参数类型相匹配的类型/code>
因此,虽然对于内置数据类型,
*&x
与x
相同,但对于用户定义类型来说,它可能不同。CComBSTR
might have overloaded theoperator *
oroperator &
to return a type which matches the parameter type received byGetMenuString()
So while
*&x
is same asx
for built-in data types, it may not be the same for user defined types.CComBSTR
上的operator&
已重载并返回BSTR*
,因此取消引用它可以为您提供所需的类型,即BSTR< /代码>。
operator&
onCComBSTR
is overloaded and returns aBSTR*
, so dereferencing it gives you the type you need, i.e. aBSTR
.如果它不能编译,那么你应该有一个有意义的错误消息?
该函数定义如下,想要
BSTR&
:CComBSTR
类不会强制转换为BSTR&
本身,而是通过&运算符
后跟* 运算符
确实如此。If it does not compile, then you should have a meaningful error message?
The function is defined as follows and wants
BSTR&
:CComBSTR
class does not cast toBSTR&
itself, but through& operator
followed by* operator
it does.