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

时间:2016-01-31 03:57:32

标签: c++ struct

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

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,在不同的位置(中心)和半径。 我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您无需为此修改现有结构。

您只需声明两个或三个或多个实例,然后在每个实例中分别设置不同的位置尺寸,如:

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;
相关问题