什么是C ++中的> *运算符? [英] What is ->* operator in C++?

查看:453
本文介绍了什么是C ++中的> *运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
}


解决方案

code> - > * 运算符是二进制运算符(不可重载)。它被解释为一个普通的二进制运算符,所以在你原来的情况下,为了调用该运算符,你必须做像

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

在Piotr的答案适用于内置运算符,而不是您的超载运算符。在您添加的示例中调用的还是内置运算符,而不是您重载的。为了调用重载的操作符,你必须做我在上面的例子中做的。


C++ continues to surprise me. Today i found out about the ->* operator. It is overloadable but i have no idea how to invoke it. I manage to overload it in my class but i have no clue how to call it.

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;
}

edit:

Thanks to the answer. To call the overloaded function i write

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

解决方案

The overloaded ->* operator is a binary operator (while .* is not overloadable). It is interpreted as an ordinary binary operator, so in you original case in order to call that operator you have to do something like

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

What you read in the Piotr's answer applies to the built-in operators, not to your overloaded one. What you call in your added example is also the built-in operator, not your overloaded one. In order to call the overloaded operator you have to do what I do in my example above.

这篇关于什么是C ++中的> *运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆