简体   繁体   中英

I'm trying to read in class pointers to a vector with a for loop, but it only works if I declare object inside loop

So my code only works when I read in the data in the loop with the shape pointer variable declared inside it.

std::vector<shape*> objList; 
for(int i = 0; i<10; i++) {
        shape* sphere = new Sphere(keskitalo::Vec3D(0,0,-10), 0.5); 
        sphere->setCenter(keskitalo::Vec3D(i - 5, i - 5, -10));
        objList.push_back(sphere);
    }

I feel like this isn't the best practice, and I want to declare it like this.

std::vector<shape*> objList; 
shape* sphere = new Sphere(keskitalo::Vec3D(0,0,-10), 0.5); 
for(int i = 0; i<10; i++) {
        sphere->setCenter(keskitalo::Vec3D(i - 5, i - 5, -10));
        objList.push_back(sphere);
    }

When I use this bottom set of code the whole vector gets set to the last iteration of the for loop, and it doesn't make any sense. Everything gets set to [4,4,-10]

Here is the code for all the functions I use. Also, the Vec3D variable is just a vector of size three.

void shape::setCenter(keskitalo::Vec3D center){    //in shape class
    m_center = center;
}

Sphere::Sphere(keskitalo::Vec3D center, double radius)  //constructor for sphere class.
        :m_center(center),
         m_radius(radius){}

Idk if there's a better way of doing this.

objList is a list of pointers. The value you're appending to objList is a pointer to a sphere, and while you do change the value of that sphere, the value you're pushing the list isn't a copy of the underlying sphere object, it's a copy of the sphere object's address. The address remains unchanged, so what you end up with is a list of 10 pointers, all pointing to the same sphere object in memory, which was last modified by the final iteration of the for loop.

If your vector must be of type shape* and not shape , then there is no reason not to use the first method. In this case, you create a new sphere every iteration, just like you need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM