在结构 C++ 中创建对象的多个实例

Creating multiple Instances of an Object in Structure C++

本文关键字:实例 创建对象 结构 C++      更新时间:2023-10-16

我有一个结构来生成单个圆形对象,代码如下:

struct point_struct {
/// Constructor
point_struct() {
    x = 0; y = 0; x0 = 0; y0 = 0; U = 0; V = 0; }
/// Elements
double x, y, x0, y0, U, V; 
};

循环对象的结构

struct particle_struct {
/// Constructor
particle_struct() {
    num_nodes = particle_num_nodes;
    radius = particle_radius;
    center.x = particle_center_x;
    center.y = particle_center_y;
    center.x0 = particle_center_x;
    center.y0 = particle_center_y;
    node = new node_struct[num_nodes];
    // The initial shape of the object is set in the following.
    // For a cylinder
  for (int n = 0; n < num_nodes; ++n) {         
     node[n].x = center.x + radius * cos(2. * M_PI * (double)n / num_nodes);
        node[n].x0 = center.x + radius * cos(2. * M_PI * (double)n / num_nodes);
        node[n].y = center.y + radius * sin(2. * M_PI * (double)n / num_nodes);
        node[n].y0 = center.y + radius * sin(2. * M_PI * (double)n / num_nodes);
/// Elements
int num_nodes; // number of surface nodes
double radius; // object radius
point_struct center; // center node
point_struct *point; // list of nodes
};

从这段代码中,我只能生成一个"圆形对象",但我想在不同的位置(中心)和半径生成更多可能是 2、3 个 ..我该怎么做?

您不需要为此修改现有结构。

你只需要声明两个或三个,或者,无论你想要多少实例,然后在每个实例中分别设置不同的位置大小,如下所示:

particle_struct particle1, particle2, particle3;

然后为centerradius以及您想要的任何其他内容提供值,例如:

particle1.center.x = 3.2;
particle1.center.y = 2.6;
particle1.radius = 12.2

等等...其他人也是如此:

particle2.center.x = 5.9;
particle2.center.y = 9.3;
particle2.radius = 7.8;
...

或者像这样:

particle_struct* particle = new particle_struct[SIZE];

particle_struct particle[SIZE];

然后给出 centerradius 或任何特征的值,例如:

particle[0].radius = 1.0;
particle[0].center.x = 0.0;

也许你应该创建一个包含多个particle_struct实例的新类,例如:

class multi_particle {
     std::vector<particle_struct> many_circular_objects;
public:
     // etc