使用默认值的动态内存分配 [英] Dynamic memory allocation with default values

查看:96
本文介绍了使用默认值的动态内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

main如果我调用

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

现在,如果我想定义一个对象数组,我们该怎么做。
如果我使用operator new
动态创建对象,我们如何做呢?

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

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

推荐答案

您不能这样做。

如果要动态分配数组,它必须是一个默认可构造的对象。这意味着,它需要一个没有参数的构造函数,这是将要使用的参数。

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.

这篇关于使用默认值的动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆