我正在尝试扩展我在 C++ 方面的知识,并试图在 openFrameworks 中找出以下用于碰撞检测的函数,并注意到一些我以前从未见过的特殊奇怪模式,这是代码:
void addForce(float targetX, float targetY, float radius, float scale) {
std::deque<Tree*> toProcess;
toProcess.push_back(this);
float xd, yd, length, effect;
float sqradius = radius * radius;
while(!toProcess.empty()) {
Tree& curTree = *(toProcess.front());
toProcess.pop_front();
if(targetX > curTree.minX - radius && targetX < curTree.maxX + radius &&
targetY > curTree.minY - radius && targetY < curTree.maxY + radius) {
if(curTree.nParticles) {
for(int i = 0; i < curTree.nParticles; i++) {
Particle& curParticle = *(curTree.particles[i]); //IS IT PASSING A REFERENCE TO A POINTER OF A METHOD CALLED .particles[i]????????
xd = curParticle.x - targetX;
yd = curParticle.y - targetY;
if(xd != 0 && yd != 0) {
length = xd * xd + yd * yd;
if(length < sqradius) {
length = sqrtf(length);
xd /= length;
yd /= length;
effect = 1 - (length / radius);
effect *= scale;
curParticle.xf += effect * xd;
curParticle.yf += effect * yd;
}
}
}
} else if(curTree.hasChildren) {
toProcess.push_back(curTree.nw);
toProcess.push_back(curTree.ne);
toProcess.push_back(curTree.sw);
toProcess.push_back(curTree.se);
}
}
}
}
正如您所看到的以下行:
Particle& curParticle = *(curTree.particles[i]);
将引用(?)传递给类(?)的指针。
你也可以在这里看到:
Tree& curTree = *(toProcess.front());
这里是否将 curTree 取消引用到双端队列的前面(?)
如果某些 C++ 大师可以向我解释这一点,我将非常感激。提前致谢:)
最佳答案
您只需查看对象声明即可回答您的问题:
std::deque<Tree*> toProcess;
因此,toProcess
是指针的双端队列。现在,查看 front()
的文档:http://en.cppreference.com/w/cpp/container/deque/front
成员函数返回对第一项的引用。在您的情况下,它是对指向 Tree
的指针的引用,可以将其复制到容器的 value_type
中。请参阅 deque
定义的类型定义/别名的文档:http://en.cppreference.com/w/cpp/container/deque
在 C++98 中:
Tree *front = toProcess.front();
在 C++11 中:
auto front = toProcess.front();
注意事项:
- 无论哪种情况,堆栈变量都包含一个指针
- 指针的值从对指针的引用复制
- 复制指针很便宜(而且很常见),因为它们占用机器寄存器
关于C++ 类&类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25231779/