如何在 for 循环中调用参数化构造函数

How can I call a parameterized constructor inside a for loop.

本文关键字:调用 参数 构造函数 循环 for      更新时间:2023-10-16

我创建了一个参数化构造函数区域。我使用面积来初始化对角线点。在 int 主部分中,我无法调用构造函数。请更正我的代码并解释错误:

int main()
{
 int ab,p,q,r,s,l,m,n,o;
  cout<<"Enter the number of rectangles: ";
  cin>>ab;
  for (int i=0; i<ab; i++)
   {
     cout<<"For rectangle "<<i+1<<endl;
     cout<<"Enter the starting and ending values of the 1st diagonal: ";
     cin>>p>>q>>r>>s;
     cout<<"Enter the starting and ending values of the 2nd diagonal: ";
     cin>>l>>m>>n>>o;
     area obj[i](p,q,r,s,l,m,n,o);
     obj[i].findArea();
     obj[i].display();
    }
  return 0;
}

写:)

 area obj(p,q,r,s,l,m,n,o);
 obj.findArea();
 obj.display();

至于声明

area obj[i](p,q,r,s,l,m,n,o);

那么你可能不会以这种方式初始化数组。在循环中定义数组是没有意义的。

假设数组obj应该在循环之外使用,我建议改用在循环之前声明的std::vector。然后,您有两种选择:

  1. 声明向量并保留足够的内存(因此在添加新元素时不必重新分配数据),然后调用 emplace_back 添加新元素。

    std::vector<area> obj;
    obj.reserve(ab);
    for (int i=0; i<ab; i++)
    {
        ...
        obj.emplace_back(p,q,r,s,l,m,n,o);
    }
    
  2. 声明具有正确大小(ab)的向量,并默认构造所有元素,然后使用简单赋值将实际对象复制到适当的位置。这要求area可以是默认构造的,并且可以是复制赋值或移动赋值运算符。

    std::vector<area> obj{ab};
    for (int i=0; i<ab; i++)
    {
        ...
        obj[i] = area(p,q,r,s,l,m,n,o);
    }
    

如果你想要数组(或向量),并且循环中的每个对象都应该存在于循环中,循环后不需要使用任何内容,只需向构造函数声明具有正确参数的对象: 有关如何执行此操作,请参阅莫斯科的 Vlad 的答案。