这个运算符 ->* 的名称是什么?

What is name of this operator ->*?

本文关键字:是什么 运算符 gt      更新时间:2023-10-16

我看过一个例子。 在该示例中,有一行类似 x->*y . 这是什么? ->* .我是C++编程新手,对运算符了解不多。有人能描述一下吗?

它被称为"指向指针成员的指针",并且是"指向成员的指针"类型运算符之一(除了.*之外,还有"指向对象成员的指针")。

当您获取成员变量或类函数的地址时,您可以使用它,然后您希望访问该变量或在该类的实例上调用该函数,给定指向该实例的指针(如香草数据或函数指针,但指向类成员)。

下面是使用函数指针的示例:

#include <cstdio>
using namespace std;
class Example {
public:
  Example (int value) : value_(value) { }
  void printa (const char *s) { printf("A %i %sn", value_, s); }
  void printb (const char *s) { printf("B %i %sn", value_, s); }
private:
  int value_;
};
// print_member_ptr can point to any member of Example that
// takes const char * and returns void. 
typedef void (Example::* print_member_ptr) (const char *);
int main () {
  print_member_ptr ptr;
  Example x(1), y(2), *p = new Example(3), *q = new Example(4);
  ptr = &Example::printa;
  // .*ptr and ->*ptr will call printa
  (x.*ptr)("hello");
  (y.*ptr)("hello");
  (p->*ptr)("hello");
  (q->*ptr)("hello");
  ptr = &Example::printb;
  // now .*ptr and ->*ptr will call printb
  (x.*ptr)("again");
  (y.*ptr)("again");
  (p->*ptr)("again");
  (q->*ptr)("again");
}

输出为:

A 1 hello
A 2 hello
A 3 hello
A 4 hello
B 1 again
B 2 again
B 3 again
B 4 again

有关更多详细信息,请参阅 http://en.cppreference.com/w/cpp/language/operator_member_access。

它是 a 指向的对象 b 指向的成员。

语法

a->*b

作为 K 的成员

R &operator ->*(K a, S b);

类外部定义

R &K::operator ->*(S b);

在维基百科上查看更多信息。