简体   繁体   English

C ++重载运算符->()不被调用?

[英]C++ overloaded operator->() not being called?

Can anyone please explain why the overloaded operator -> for class Foo is not being called from a pointer of type Foo *? 谁能解释为什么没有从Foo *类型的指针调用Foo类的重载运算符->吗?

#include <iostream>
using namespace std;

class Foo {
public:
Foo * operator -> () {
    cout << "calling Foo * operator -> ()\n";
    return this;
}
    int x;
};


void main() {
    Foo f;
    Foo * pF = &f;
    pF->x;                  // Why is overloaded operator-> not being called here?
    (pF->operator->())->x;  // This works.

    cout << "End test.\n";
}

Why is overloaded operator-> not being called here? 为什么这里没有调用重载的operator->?

Because pF is a pointer, not a Foo instance. 因为pF是指针,而不是Foo实例。 You have overloaded operator-> for Foo , not Foo* . 您对Foo而不是Foo*重载了operator-> You may call your overloaded operator-> directly on f . 您可以直接在f上调用重载的operator->

f->x;

You may not overload operator-> for Foo* or any other pointer type. 您不能为Foo*或任何其他指针类型重载operator->

You overloaded it for Foo , not for Foo* (which is impossible). 您为Foo重载了它,而不是为Foo*重载了(这是不可能的)。

This would have worked: 这本来可以工作:

(f.operator->())->x;

Or, of course: 或者,当然:

f->x;

Being able to use that short syntax is the entire purpose of the overload, no? 能够使用这种短语法是重载的全部目的,不是吗? Although it's quite confusing to just return a pointer to the same object you invoked the operator on. 尽管仅返回指向您在其上调用了该运算符的对象的指针是很令人困惑的。

You have overloaded "point-to" operator of the type Foo , not type Foo* . 您已经重载了类型为Foo “指向”运算符,而不是类型为Foo*

class Foo {
public:
    // Overload 'point-to' operator of 'Foo'
    Foo * operator -> () {
        cout << "calling Foo * operator -> ()\n";
        return this;
    }
    int x;
};

Example of usage: 用法示例:

Foo f;
f.operator->();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM