【问题标题】:What is ->* operator in C++?什么是 C++ 中的 ->* 运算符?
【发布时间】:2010-12-19 06:40:01
【问题描述】:

C++ 继续让我感到惊讶。 今天我发现了 ->* 运算符。它是可重载的,但我不知道如何调用它。我设法在课堂上重载它,但我不知道如何调用它。

struct B { int a; };

struct A
{
    typedef int (A::*a_func)(void);
    B *p;
    int a,b,c;
    A() { a=0; }
    A(int bb) { b=b; c=b; }
    int operator + (int a) { return 2; }
    int operator ->* (a_func a) { return 99; }
    int operator ->* (int a) { return 94; }
    int operator * (int a) { return 2; }
    B* operator -> () { return p; }


    int ff() { return 4; }
};


void main()
{
    A a;
    A*p = &a;
    a + 2;
}

编辑:

感谢回答。调用我写的重载函数

void main()
{
    A a;
    A*p = &a;
    a + 2;
    a->a;
    A::a_func f = &A::ff;
    (&a->*f)();
    (a->*f); //this
}

【问题讨论】:

  • 不,在这种情况下您不调用重载运算符。你所说的是内置的。您的重载运算符需要 int 作为第二个参数。
  • @AndreyT:更新结构以反映新的 main。
  • @acidzombie24:好的,现在你终于调用了重载版本。同样,您可以通过 a->*42 执行此操作而无需任何更新,正如 sellibitze 建议的那样。

标签: c++ operator-overloading operator-arrow-star


【解决方案1】:

就像.* 一样,->* 与指向成员的指针一起使用。有一整节 on C++ FAQ LITE 专门用于指向成员的指针。

#include <iostream>

struct foo {
    void bar(void) { std::cout << "foo::bar" << std::endl; }
    void baz(void) { std::cout << "foo::baz" << std::endl; }
};

int main(void) {
    foo *obj = new foo;
    void (foo::*ptr)(void);

    ptr = &foo::bar;
    (obj->*ptr)();
    ptr = &foo::baz;
    (obj->*ptr)();
    return 0;
}

【讨论】:

    【解决方案2】:

    重载的-&gt;* 运算符是二元运算符(而.* 不可重载)。它被解释为一个普通的二元运算符,所以在你原来的情况下,为了调用那个运算符,你必须做类似的事情

    A a;
    B* p = a->*2; // calls A::operator->*(int)
    

    您在 Piotr 的回答中读到的内容适用于 内置 运算符,而不适用于您的重载运算符。您在添加的示例中调用的也是 built-in 运算符,而不是重载的运算符。为了调用重载运算符,您必须按照我在上面的示例中所做的操作。

    【讨论】:

    • 您对 piotr 的回答是正确的,但有了它,我想出了如何调用重载运算符,如我编辑的问题所示
    【解决方案3】:

    与任何其他运算符一样,您也可以显式调用它:

    a.operator->*(2);
    

    【讨论】:

      猜你喜欢
      • 2010-12-11
      • 2014-10-19
      • 2017-08-07
      相关资源
      最近更新 更多