gpt4 book ai didi

c++ - 如何制作一个实例化类并将它们排序在地址列表中的循环?

转载 作者:行者123 更新时间:2023-11-30 03:14:21 26 4
gpt4 key购买 nike

考虑 2 个变量(多边形的数量及其坐标):

int numberPoly= 2;
float polycoord[18]= {0,50,0,0,0,0,50,0,0,0,50,0,50,50,0,50,0,0};

,模型类(旨在将多边形类存储到列表中):

class model{
public:
model();
void affect(int id, int address){
polyclasses[id]=address;
}
private:
string name;
vector<int> polyclasses;
};

,一个多边形类(我必须在模型的多类列表中排序):

class polygone {
public:
polygone();
void affect(int id, int coord){
ABC[id]=coord;
}
private:
int id;
float ABC[9]={0.0};
};

我想编写一个函数(参见“builder”)来实例化 n 个 Polygon 类并在数组(Model 类中的“polyclasses”)中对它们进行排序(使用它们的内存地址,如 id)。所以,我没有到达。这是我的一些未完成的构建器函数:

void builder(){
int from = 0; int subfrom = 0;
for(int i=0; i < numberPoly - 1; i++){
from = 0; subfrom = 0;
polygone poly();
!!! need to put that instance in Model's polygon list !!!
...
for(int j=from; j < (polycoord.size())-1; j++){
poly.affect(subfrom, polycoord[j]) ...
subfrom++;
}
from += 3;
}
}

这是我的第一个 C++ 项目。我正在编写一个轻型 2d 引擎。

最佳答案

您需要在 vector 中存储实例指针,并使用 new 关键字分配对象。在您的模型析构函数中,您需要删除该对象以避免内存泄漏。

// Model.h
// Class name should begin with uppercase by convention
class Model{
public:
Model();
~Model();
void builder();
// Implementation should go in cpp file
void affect(int id, int address);
private:
// Having a m_ prefix on private variable is useful to make your code more readable so a reader can easily know if a variable is private or not
string m_name;
vector<Polygon*> m_polyclasses;
};

// Polygone.h
class Polygone {
public:
Polygone();
// Don't forget destructor
~Polygone();
// Implementation should go in cpp file
void affect(int id, int address);
private:
int m_id;
// Use std::array in C++ and give meaningful name to your variable
// float m_ABC[9]={0.0}; is replaced by :
std::array<float, 9> m_coordinates;
};

// Model.cpp
void Model::builder() {
int from = 0; int subfrom = 0;
for(int i=0; i < numberPoly - 1; i++){
from = 0; subfrom = 0;
Polygone * poly = new Polygone();
// A pointer of poly is now stored in Model
this->polyclasses.push_back(poly);
// Your polygone object should initialized in the constructor or in a member function of the class Polygone.
for(int j=from; j < (polycoord.size())-1; j++){
poly->affect(subfrom, polycoord[j]) ...
subfrom++;
}
from += 3;
}
}

Model::~Model() {
for(auto p: this->polyclasses) {
// Avoid memory leak
delete p;
}
this->polyclasses.clear();
}

您还可以存储 std::unique_ptr而不是一个普通的指针。在这种情况下,您不需要delete

关于c++ - 如何制作一个实例化类并将它们排序在地址列表中的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57902068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com