[英]I am trying to create a vector of classes and then name each class with a for loop
[英]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
所以我的代碼只有在我讀入循環中的數據時才有效,其中聲明了形狀指針變量。
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);
}
我覺得這不是最佳做法,我想這樣聲明。
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);
}
當我使用這組底部代碼時,整個向量被設置為 for 循環的最后一次迭代,這沒有任何意義。 一切都設置為 [4,4,-10]
這是我使用的所有功能的代碼。 此外,Vec3D 變量只是一個大小為 3 的向量。
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){}
如果有更好的方法可以做到這一點。
objList
是一個指針列表。 您附加到objList
的值是指向球體的指針,當您更改該球體的值時,您推送列表的值不是底層球體 object 的副本,它是球體對象的地址。 地址保持不變,所以你最終得到的是一個包含 10 個指針的列表,它們都指向 memory 中的同一個球體 object,最后一次修改是由for
循環的最終迭代。
如果您的向量必須是shape*
而不是shape
類型,那么沒有理由不使用第一種方法。 在這種情況下,您每次迭代都會創建一個新球體,就像您需要的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.