C++返回指向成员的指针

Tho*_*ing 1 c++

返回类型"指向成员的指针"的语法是什么?

struct Point {
    int x;
    int y;
    int z;
};

// compiles
decltype(&Point::x) getX () {
   return &Point::x;
}

// does not compile... how to do this without decltype?
int (Point::*) getX () {
   return &Point::x;
}


// Use case:
Point p, q;
auto pm = getX();
p.*pm = 1;  // p.x = 1
q.*pm = 2;  // q.x = 2
Run Code Online (Sandbox Code Playgroud)

ana*_*lyg 7

你不需要括号:

int Point::* getX () {
   return &Point::x;
}
Run Code Online (Sandbox Code Playgroud)

想象一下使用带有常规指针的括号:

int (*) getX() // compiler says WTF
{
   static int x; 
   return &x;
}
Run Code Online (Sandbox Code Playgroud)


T.C*_*.C. 5

删除多余的括号并将类型更改为int:

int Point::* getX () {
   return &Point::x;
}
Run Code Online (Sandbox Code Playgroud)

演示,因为coliru此刻正在下降.