c++速记运算符->操作员()
假设我有:
Foo foo;
有这个的简写吗?
foo.operator->().operator()(1, 2);
Suppose I have:
Foo foo;
is there a shorthand for this?
foo.operator->().operator()(1, 2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯...是的。 更短形式看起来就像
消除
operator ->
部分...从您到目前为止提供的信息来看,这是不可能的,但如果它被实现我可以猜测它的实现方式(从你的表达来看),那么你无法消除它。在 C++ 中,表达式中重载
->
运算符的使用被解释为重复重载->
调用链,最终以内置结束>->
调用。这意味着在某些时候重载的->
必须返回一个指针。您重载的->
显然不会返回指针。因此,为了使用它,您别无选择,只能将其明确拼写为operator ->()
。Well... Yes. The shorter form would look as
As for eliminating the
operator ->
part... From the information you supplied so far it is impossible to say, but if it is implemented the way I can guess it is implemented (judging from your expression), then you can't eliminate it.In C++ the use of overloaded
->
operator in an expression is interpreted as a chain of repetitive overloaded->
calls, which eventually ends in a built-in->
invocation. This means that at some point the overloaded->
must return a pointer. Your overloaded->
obviously doesn't return a pointer. So, in order to use it you have no other choice but to spell it out explicitly asoperator ->()
.假设您实际上意味着
foo.operator->().operator()(1, 2)
,并且您可以控制Foo
类 code>,更简单的形式是(*foo)(1, 2)
。它需要operator*
来定义它,但因为我们通常期望foo->bar
等价于(*foo).bar
,看来很有道理。如果您的
Foo
是某种智能指针类,它指向定义operator()
的对象,那么这将是调用该对象的 <代码>运算符()。但是如果没有更多细节(并且如果您没有提供实际上有效的 C++ 表达式 - 您编写的
operator(1, 2)
不可能有效),就不可能回答您的问题。我只是猜测你想做什么。Assuming you actually meant
foo.operator->().operator()(1, 2)
, and that you have control over the classFoo
, a simpler form would be(*foo)(1, 2)
. It requires theoperator*
to that defined though, but since we usually expectfoo->bar
to be equivalent to(*foo).bar
, it seems reasonable.If your
Foo
is a smart pointer class of some sort, which points to an object which defines anoperator()
, this would be the most concise way of calling the object'soperator()
.But without more detail (and without you providing an expression that's actually valid C++ -- there's no way in which
operator(1, 2)
as you wrote it can be valid), it's impossible to answer your question. I'm just guessing at what you're trying to do.好吧,不,但是,假设您对该类具有写权限,您可以定义另一个调用operator()的成员函数,然后您会得到类似的结果:
您发现自己处于这个位置,这表明您(或写这个类的人)对于运算符重载有点太可爱了。
Well, no, but, assuming you have write permissions to the class, you could define another member function that calls operator(), and then you'd have something like:
That you find yourself in this position is a sign that you (or the person who wrote this class) is being a bit too cute with operator overloading.