在结构 C++ 中创建对象的多个实例
Creating multiple Instances of an Object in Structure C++
我有一个结构来生成单个圆形对象,代码如下:
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;
然后为center
和radius
以及您想要的任何其他内容提供值,例如:
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];
然后给出 center
和 radius
或任何特征的值,例如:
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
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 为什么我不能引用指向实例化对象的函数的指针?
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 为什么在使用指针时不采用类成员的默认值,而不是直接实例化对象时?
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- C++阻止用户创建对象实例
- 在另一个对象 B 中创建对象 A 时,对象 A 是否是对象 B 的本地对象,对象 A 是否会存在于对象 B 的实例化之外?
- 为什么当我在构造函数中创建线程时,实例化对象和对象的指针的行为不同
- 使用std::shared_ptr对象实例创建boost::线程
- 在结构 C++ 中创建对象的多个实例
- 在方法中实例化对象vs.创建类成员