您可以手动调用箭头(->)运算符函数吗?
如果我有一个 Foo *foo
,我可以说 foo->bar()
。是否可以手动调用operator->()
函数?如果是这样,我将如何传递它 bar()
?
如果改为 Foo foo
会有什么不同吗?
也许像 foo.operator->(bar) 之类的东西?
If I have a Foo *foo
, I can say foo->bar()
. Is it possible to call the operator->()
function manually? And if so, how would I pass it bar()
?
Does it make a difference if it is Foo foo
instead?
Maybe something like foo.operator->(bar)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你可以。通过重载
->
,foo->bar()
表达式被编译器解释为foo.operator->()->bar( )
。这正是“手动”调用它的方式:foo.operator->()->bar()
。如果您的重载
operator ->
函数“正确”实现,即它返回也支持运算符->
的内容,那么使用“手册”就没有多大意义了语法,因为它与“非手动”做同样的事情。您需要“手动”语法的唯一情况是,重载的
operator ->
的实现返回不支持->
的其他应用程序的内容。例如,int
值。Yes, you can. With overloaded
->
thefoo->bar()
expression is interpreted by the compiler asfoo.operator->()->bar()
. And this is exactly how you can call it "manually":foo.operator->()->bar()
.If your overloaded
operator ->
function is implemented "properly", i.e. it returns something that also supports operator->
then there's not much point in using the "manual" syntax, since it is doing the same thing as the "non-manual" one.The only case you'd need the "manual" syntax is when your implementation of overloaded
operator ->
returns something that does not support another application of->
. Anint
value, for example.是的。
Yes.
没有运算符->()函数,因为示例中的
foo
是一个指针。对于指针,->
的行为由语言定义。如果类型
Foo
有一个operator->()
函数,并且您定义了Foo *foo
,您可以这样做来调用operator->()
函数:或者您可以使用直接调用语法:
There is no operator->() function because
foo
in your example is a pointer. For pointers, the behavior of->
is defined by the language.If the type
Foo
has anoperator->()
function, and you haveFoo *foo
defined, you can do this to call theoperator->()
function:Or you can use the direct call syntax: