samedi 18 juin 2022

C++ Classes: Member variables not updating when using a vector of objects [duplicate]

I have declared a vector array of objects called bn of class Particle. For testing purposes, I started with one object-element in the array.

Class member functions:

void Particle::p(float pos_x, float pos_y, float mass)
{
    m = mass;
    x = pos_x;
    y = pos_y;
    velx = 0;
    vely = 0;
    radius = calc_rad();
}
float Particle::calc_rad()
{
    radius = 10 * cbrt(m / density);

    return radius;
}
void Particle::move(float t)
{
    x += velx * t;
    y += vely * t;
}

Class declaration:

class Particle
{
public:
    float m;
    float x;
    float y;
    float velx;
    float vely;
    float radius;
    float density = 100;

    void p(float pos_x, float pos_y, float mass);
    float calc_rad();
    void move(float t);
};

main():

int main()
{   
    std::vector <Particle> bn(1);
    
    bn[0].p(500, 500, 1);
    
    float t = 1;
    int it = 0;

    for(int j = 0; j < 10; j++)
    { 
        for (Particle i : bn)
        {   
            i.velx = 1;
            i.vely = 1;
            i.move(t);
            std::cout << i.x << std::endl;
        }
        
    }
}

I want to update the member variables x and y of objects in bn. But the values are not changing. I tried declaring a single object without any vectors and it works fine. But I need an array of objects. Can someone tell me what the issue is or whether I'm missing something?

Aucun commentaire:

Enregistrer un commentaire