什么是::*在C++中

What is ::* in C++?

本文关键字:C++ 什么      更新时间:2023-10-16

当我面对时,我正在阅读一个基本的C++教程

::*

在以下代码中。我可以知道那是什么吗:

class A {
public:
protected:
  int i;
};

class B : public A {
  friend void f(A*, B*);
  void g(A*);
};
void f(A* pa, B* pb) {
//  pa->i = 1;
  pb->i = 2;
//  int A::* point_i = &A::i;
  int A::* point_i2 = &B::i;
}
void B::g(A* pa) {
//  pa->i = 1;
  i = 2;
//  int A::* point_i = &A::i;
  int A::* point_i2 = &B::i;
}
void h(A* pa, B* pb) {
//  pa->i = 1;
//  pb->i = 2;
}
int main() { }

根据我目前对C++的了解,下面是什么?

int A::* point_i2

point_i2是指向成员的指针。这意味着它指向在类A中声明的int成员变量。

int A::* point_i2 = &B::i;

之后,当您有一个随机的AB对象时,您可以访问point_i2指向的成员

B b;
b.*point_i2 = ...;

point_i2的上述初始化之后,这将改变b.i

以与&*相同的方式思考ClassName::*:它只是另一个"类似指针/引用的工具",您可以在声明中使用它来指定您声明的内容