简体   繁体   中英

Creating multiple Instances of an Object in Structure C++

I have a structure to generate single circular object, the code is as :

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; 
};

/// Structure for Circular object

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
};

From this code I can only generate one "circular object" but I would like to generate more may be 2, 3 .. at different locations (centers) and radii. How can I do this?

Perhaps you should create a new class that holds multiple particle_struct instances, such as :

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

You do not need to modify your existing structure for that.

You just have to declare two or three or, however much instances you want, and then set the different location and sizes in each of them separately like:

particle_struct particle1, particle2, particle3;

and then give values for center and radius and whatever else you want, one by one like:

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

and so on... likewise for the others:

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

or like this:

particle_struct* particle = new particle_struct[SIZE];

or

particle_struct particle[SIZE];

and then give values of center and radius or any characteristics like:

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

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