开发者

Using new to allocate an array of class elements with an overloaded constructor in C++

As an example say I have a class foo that does not have a default constructor but one that looks like this

foo:foo(int _varA,int _varB)
{
   m_VarA = _varA;
   m_VarB = _varB;
}

How would I allocate an array of these.

I seem to remember trying somthing like this unsuccessfully.

foo* MyArray = new foo[100](25,14).

I don't think this will work either.

foo* MyArray = new foo[100](25,14)

Can this be done? I typically do this by writing the default constructor using some preset values for _varA and _varB. Then adding a function to reset _varA and _varB for each element but that will not开发者_运维百科 work for this case.

Thanks for the help.


Your first choice should be to ignore the fact that new[] even exists, and use an std::vector instead:

std::vector<foo> MyArray(100, foo(25,14));


If you are to be able to allocate an array of a class (directly, using new[]), the class must have a default constructor. No default constructor, no dynamic arrays.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜