什么是C++中的 - >*运算符?

21 c++ operator-overloading operator-arrow-star

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

谢谢你的回答.要调用我写的重载函数

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

Cat*_*lus 15

就像.*,->*用于指向成员的指针.关于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;
}
Run Code Online (Sandbox Code Playgroud)


AnT*_*AnT 10

重载->*运算符是二元运算符(虽然.*不可重载).它被解释为一个普通的二元运算符,所以在原始情况下,为了调用该运算符,你必须做类似的事情

A a;
B* p = a->*2; // calls A::operator->*(int)
Run Code Online (Sandbox Code Playgroud)

您在Piotr的答案中读到的内容适用于内置运算符,而不适用于您的重载运算符.您在添加的示例中调用的内容也是内置运算符,而不是您的重载运算符.为了调用重载操作符,你必须按照我上面的例子中的操作.

  • +1.我也会赞成piotr的一个.但它漏了:) (2认同)