简体   繁体   English

具有默认值的动态内存分配

[英]Dynamic memory allocation with default values

class A
{
private:
int m_nValue;
public:
A()
{
m_nValue = 0;
}
A(int nValue)
{
m_nValue = nValue);
~A()
{}
}

Now in main if i call 现在在主要如果我打电话

A a(2);// 2 will be assigned for m_nValue of object A.

Now how do we do this if i want to define an array of objects. 现在,如果我想定义一个对象数组,我们该怎么做。 Also how do we do this if i dynamically create objects using operator new like 另外,如果我使用新的运算符new动态创建对象,我们该怎么做?

A *pA;
pA = new A[5];// while creating the object i want the parameterised constructor to be 

//called

I hope the question is clear. 我希望问题清楚。 Do let me know if more explanation is needed 让我知道是否需要更多解释

You cannot do this. 你不可以做这个。

If you want to dynamically allocate an array, it has to be a default-constructable object. 如果要动态分配数组,则它必须是可默认构造的对象。 This means, it needs to have a constructor with no parameters, which is the one that will be used. 这意味着,它需要一个没有参数的构造函数,这是将要使用的构造函数。

if i want to define an array of objects 如果我想定义一个对象数组

This is C++, you don't want arrays ;-) 这是C ++,您不需要数组;-)

std::vector<A> v(5, A(2));

You normally can't do this, as array objects are default constructed, but one quick hack is you can create a subclass whose default constructor passes on the parameter(s) you want to the base class. 通常无法执行此操作,因为数组对象是默认构造的,但是一个快速的技巧是可以创建一个子类,该子类的默认构造函数将您想要的参数传递给基类。

template<int I>
class B : public A
{
public:
     B() : A(I) { }
};
...

A *pA;
pA = new B<42>[5];

Abusing inheritance in such a fashion is frowned upon in some circles, however. 但是,这种方式滥用继承在某些圈子中是不受欢迎的。

If you want to define an array, you can use the aggregate initializer 如果要定义数组,则可以使用聚合初始化程序

A a[5] = { 1, 2, 3, 4, 5 };

Note though that aggregate initialization follows copy-initialization semantics, so for each element it will be equivalent to 请注意,尽管聚合初始化遵循复制初始化语义,所以对于每个元素,它都等效于

A a1 = 1;

not to your original 不是你原来的

A a1(1);

As for the new-expression... The only initializer you can supply in the array new-expression is the empty () initializer, which triggers value-initialization. 至于new-expression ...,您可以在数组new-expression中提供的唯一初始化器是empty ()初始化器,它将触发值初始化。 No other initializers are supported by the language at this time. 该语言目前不支持其他初始化程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM