【问题标题】:What is name of this operator ->*? [duplicate]这个操作符 ->* 的名称是什么? [复制]
【发布时间】:2014-03-23 21:58:52
【问题描述】:

我看过一个例子。在那个例子中,有一行像x->*y。它是什么? ->*。我是 C++ 编程新手,对运算符了解不多。谁能描述一下?

【问题讨论】:

  • 一点也不难检查:en.cppreference.com/w/cpp/language/operator_precedence。哦,它不是 C 的一部分。
  • 不是一个操作员。它是-> 运算符,后跟* 运算符。
  • @Barmar,它肯定是在 C++ 中,我认为你不能在 C 中使用这种语法。
  • @chris 我已经阅读了,我发现了一些运算符,例如 ->*->*。所以,我越来越困惑。是两个运算符->* 的组合还是一个运算符->*(指向成员的指针)?
  • @Felix 与 What are the Pointer-to-Member ->* and .* Operators in C++? 相同,不知道为什么重复项会被投票。

标签: c++ operators


【解决方案1】:

它被称为“指向成员的指针”,是“指向成员的指针”类型运算符之一(除了.*,“指向对象成员的指针”)。

当你获取一个类的成员变量或函数的地址时,你可以使用它,然后你想要访问该变量或在该类的实例上调用该函数,给定一个指向实例的指针(如 vanilla数据或函数指针,但指向类成员)。

下面是一个使用函数指针的例子:

#include <cstdio>
using namespace std;

class Example {
public:
  Example (int value) : value_(value) { }
  void printa (const char *s) { printf("A %i %s\n", value_, s); }
  void printb (const char *s) { printf("B %i %s\n", 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

【讨论】:

    【解决方案2】:

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

    语法

    a->*b
    

    作为K的一员

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

    外部类定义

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

    Wikipedia 上查看更多信息。

    【讨论】:

      猜你喜欢
      • 2011-03-05
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 2014-01-28
      • 2016-10-27
      • 2014-02-14
      • 1970-01-01
      • 2017-08-01
      相关资源
      最近更新 更多