How exactly does constexpr double Point::* coords[3] work? [duplicate]

ⅰ亾dé卋堺 提交于 2021-01-28 04:03:10

问题


So I've been looking at some stuff and found this thread Aliasing struct and array the C++ way

And this is the answer to the question

#include <math.h>

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

double dist(struct Point *p1, struct Point *p2) {
    constexpr double Point::* coords[3] = {&Point::x, &Point::y, &Point::z};

    double d2 = 0;
    for (int i=0; i<3; i++) {
        double d = p1->*coords[i] - p2->*coords[i];
        d2 += d * d;
    }
    return sqrt(d2);
}

Now my problem is that I have no idea what

constexpr double Point::* coords[3] = {&Point::x, &Point::y, &Point::z};

is supposed to do...

I understand that constexpr makes it a constant that is defined at compile time and double is obviously used because the struct contains doubles but the Point::* and the {&Point::x, &Point::y, &Point::z}; confuse me. First of all what is Point::*? I guess the * means it is a some kind of pointer but to what? And what are these addresses {&Point::x, &Point::y, &Point::z} ?

What exactly does this entire expression define?


回答1:


This syntax is a pointer to member, and is essentially a way to store a member to a variable and retrieve it. It's useful for a case like this, when you want to loop through a list of members.



来源:https://stackoverflow.com/questions/63284797/how-exactly-does-constexpr-double-point-coords3-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!