一个令人困惑的 typedef 涉及 class 范围

A confusing typedef involves class scope

我正在阅读 C++ 项目的代码,它包含以下形式的一些代码:

namespace ns {
    class A {};
    class B {};
}

struct C {
    typedef ns::A* ns::B::* type;
};

谁能解释一下 typedef 行的意思? type 似乎是指向 ns::B 成员的某种指针,它指向 ns::A,但我不确定。

Class AB 在真正的代码中不为空,但我认为它与这里无关。这是 live example.

ns::B::*

是指向 B 的成员变量的指针。那么ns::A*就是它的类型。

所以整个声明的意思是

B 类型 ns::A*

的指向成员变量的指针

已经回答了问题的核心。这个答案显示了如何使用这样的 typedef.

#include <iostream>
#include <cstddef>

namespace ns {

   struct A {};

   struct B
   {
      A* a1;
      A* a2;
   };
}

struct C {
   typedef ns::A* ns::B::*type;
};

int main()
{
   C::type ptr1 = &ns::B::a1;
   C::type ptr2 = &ns::B::a2;

   ns::B b1;
   b1.*ptr1 = new ns::A; // Samething as b1.a1 = new ns::A;

   return 0;
}