使用两个不同的构造函数初始化指向数组的指针
initializing pointer to array with two different constructor
>我有一个程序,我想在其中使用指针初始化类对象数组。
class xyz{};
cin>>M;
xyz *a=new xyz[M]; //this will call the constructor for each object.
问题是我在 XYZ 类中有两个构造函数。 我想使用其他构造函数初始化最后两个元素,而不是没有参数的默认构造函数。我该怎么做?
我希望 M+1 和第 M+2 项由接受参数的不同构造函数初始化。
std::vector<xyz> a(M-2);
a.push_back(xyz(...)); // xyz(...) here is a call to the
a.push_back(xyz(...)); // constructor you want to use
此代码假定 M>= 2。 当然,这不是一个安全的假设,您必须决定如何处理不合格的情况。
首先,cin<<M
是错误的。 应该是cin >> M
. 确保您的插入和提取操作员指向正确的方向。
不能使用单个间接寻址。 new
运算符将为数组中的每个对象调用默认构造函数。
如何实现目标的选项是:在所需的分配上复制所需的默认值,或创建指向对象的指针数组。
复制方法
xyz t(my_other_constructor);
xyz* a = new xyz[M];
a[M - 1] = t; // overwrite the default constructed value with the desired
双间接
xyz** a = new xyz*[M];
for (int i = 0; i < M - 1; ++i)
{
a[i] = new xyz;
}
a[M - 1] = new xyz(my_other_constructor);
理想情况下,您将使用std::vector
而不是创建手动数组。
相关文章:
- 为什么std::vector和std::valarray初始化构造函数不同
- 初始化构造函数C++中结构的向量
- C++ 中常量属性的初始化构造函数错误
- 不正确的输出和变量未用Eclipse CDT初始化构造函数
- 如何使用嵌套初始化构造函数中的一维向量初始化矩阵
- 如何通过参数初始化构造函数中的数组?
- 是否有理由使用 malloc 初始化构造函数中的指针
- 如何在 c++ 中初始化构造函数中的二维数组
- 为什么初始化构造函数列表参数时会发生异常?
- 无法初始化构造函数
- 初始化构造函数的默认参数的优选方法是什么?
- 在C++17中使用空列表初始化构造函数时发生编译错误
- C++ 初始化构造函数初始化列表中的嵌套结构?
- 初始化构造函数c++中的向量
- g++ (GCC) 4.6.0 我有以下类,我正在尝试初始化构造函数的结构成员初始化列表
- 使用字符串文本初始化构造函数中的 std::array<char,x> 成员。海湾合作委员会错误?
- 初始化构造函数C++中函数的成员指针
- 在c++中初始化构造函数中的静态成员变量时出错
- memset()初始化构造函数中的对象
- 初始化构造函数C++中的成员向量