gpt4 book ai didi

c++ - constexpr double Point::* coords[3] 究竟是如何工作的?

转载 作者:行者123 更新时间:2023-12-01 14:51:36 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Pointer to class data member "::*"

(18 个回答)


1年前关闭。




所以我一直在看一些东西,发现这个线程Aliasing struct and array the C++ way
这就是问题的答案

#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);
}
现在我的问题是我不知道是什么
constexpr double Point::* coords[3] = {&Point::x, &Point::y, &Point::z};
应该做...
我了解 constexpr使其成为在编译时定义的常量, double显然使用了,因为结构包含 double ,但 Point::*{&Point::x, &Point::y, &Point::z};迷惑我。首先什么是 Point::* ?我猜 * 表示它是某种指针,但指向什么?这些地址是什么 {&Point::x, &Point::y, &Point::z} ?
这整个表达式到底定义了什么?

最佳答案

此语法是 pointer to member , 本质上是一种将成员存储到变量并检索它的方法。当您想要遍历成员列表时,这对于这种情况很有用。

关于c++ - constexpr double Point::* coords[3] 究竟是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63284797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com