如何在 for 循环中调用参数化构造函数
How can I call a parameterized constructor inside a for loop.
我创建了一个参数化构造函数区域。我使用面积来初始化对角线点。在 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
。然后,您有两种选择:
-
声明向量并保留足够的内存(因此在添加新元素时不必重新分配数据),然后调用
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); }
-
声明具有正确大小(
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 的答案。
相关文章:
- 为什么即使我调用参数化构造函数也会调用默认构造函数?
- 什么是仅调用一次并调用参数的控制台应用
- 调用参数排列不变函数 f(i++, i++)
- 调用参数不是原子参数的函数是此代码引发异常的原因吗?
- 如何使可调用参数的签名在C++模板中可见?
- x64 函数调用参数推送/移动顺序 (MSVC)
- 如何调用参数由另一个函数生成的函数?
- 从从可调用参数创建的线程对象参数移动构造 C++11 线程
- 正确调用参数化 std::函数
- 是否允许在调用参数中使用类型名 T
- 我不知道如何调用参数为节点类型的函数
- 函数调用参数列表 (C++) 中的空格
- Valgrind 错误:系统调用参数 epoll_pwait(sigmask) 指向不可寻址的字节
- 这C++代码如何让我调用参数数量错误的函数
- 在计算后,在基类之后调用参数化构造函数
- NPAPI调用参数包装
- 在类组合中调用参数化构造函数
- 为什么在创建类对象数组时不能调用参数化构造函数?
- 如何在 for 循环中调用参数化构造函数
- 如何在PIMPL设计模式中调用参数化构造函数