C ++指向成员的指针

时间:2013-05-08 10:33:32

标签: c++ member-pointers

//#define NOT_WORKS
#define HOW(X) 0

struct A {

};

struct B {
    A a;
};

struct C {
    B b;
};

int main(int argc, char **argv) {
    A B::*ba = &B::a;       // ba is a pointer to B::a member
    B C::*cb = &C::b;       // cb is a pointer to C::b member

#ifdef NOT_WORKS

    { A C::*ca = &C::b::a; }    // error: Symbol a could not be resolved / error: ‘C::b’ is not a class or namespace
    { A C::*ca = cb + ba; }     // error: invalid operands of types ‘B C::*’ and ‘A B::*’ to binary ‘operator+’

    A C::*ca = HOW(???);        // is possible to reach C::b::a by a member pointer?

#endif

    C cptr;
    A aptr = cptr.*cb.*ba;  // is pointer inference chaining the only solution?

    return 0;
} 

如果成员指针的推理链接是到达内部成员的唯一解决方案,我可以使用模板将其封装在单个类型上吗?


现在可以使用gcc编译代码

谢谢大家

1 个答案:

答案 0 :(得分:2)

  

是否可以通过成员指针到达C :: b :: a?

排序:

C c; 
A B::*ca = &B::a;  //    usage: c.b.*ca;  
  

指针推断链接唯一的解决方案?