C++ 类和类名

c++ class& className

本文关键字:C++      更新时间:2023-10-16

我正试图扩展我在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解引用到deque的前面(?)

如果有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();

指出:

  • 堆栈变量在两种情况下都包含一个指针
  • 指针的值从引用复制到指针
  • 复制指针很便宜(也很常见),因为它们占用机器寄存器
相关文章:
  • 没有找到相关文章