4

我有一个程序,我想在其中使用指针初始化一个类对象数组。

class xyz{};
cin>>M;

xyz *a=new xyz[M];   //this will call the constructor for each object.

问题是我在类 xyz 中有两个构造函数。我想使用其他构造函数初始化最后两个元素,而不是没有参数的默认元素。我怎样才能做到这一点?

我希望第 M+1 和第 M+2 项由接受参数的不同构造函数初始化。

4

2 回答 2

4
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。当然,这不是一个安全的假设,您必须决定如何处理不合格的情况。

于 2013-09-18T20:25:05.563 回答
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而不是创建手动数组。

于 2013-09-18T20:31:40.903 回答