繁体   English   中英

堆上的C ++数组

[英]C++ Array on the heap

如果我在堆上声明一个数组,我怎样才能获得有关该数组的信息?

这是我的代码:

class Wheel
{
public:
    Wheel() : pressure(32)
    {
        ptrSize = new int(30);
    }
    Wheel(int s, int p) : pressure(p)
    {
        ptrSize = new int(s);
    }
    ~Wheel()
    {
        delete ptrSize;
    }
    void pump(int amount)
    {
        pressure += amount;
    }
    int getSize()
    {
        return *ptrSize;
    }
    int getPressure()
    {
        return pressure;
    }
private:
    int *ptrSize;
    int pressure;
};

如果我有以下内容:

Wheel *carWheels[4];
*carWheels = new Wheel[4];
cout << carWheels[0].getPressure();

当它在堆上时,如何在数组中的任何实例上调用.getPressure()方法? 另外,如果我想在堆上创建一个Wheel数组,但在堆上创建数组时使用此构造函数:

Wheel(int s, int p)

我该怎么做呢?

Wheel *carWheels[4];

是一个指向Wheel的指针数组,因此您需要使用new初始化它:

for ( int i = 0; i < sizeof(carWheels)/sizeof(carWheels[0]); ++i)
  carWheels[i]=new Wheel(); // or any other c-tor like Wheel(int s, int p)

以后你可以像这样访问它:

carWheels[0]->getPressure();

可以像上面一样检索数组的大小:

sizeof(carWheels)/sizeof(carWheels[0])

[编辑 - 更多细节]

如果你想坚持使用数组,你需要在函数调用时传递它的大小,因为数组会衰减到指针。 您可能希望保持以下语法:

void func (Wheel* (arr&)[4]){}

我希望是正确的,因为我从不使用它,但更好地切换到std :: vector。

还有数组中的裸指针,你必须记住在某些时候删除它们,数组也不能保护你免受异常 - 如果有任何发生,你将留下内存泄漏。

简单,替换

Wheel *carWheels[4];

std::vector<Wheel*> carWheels(4);
for ( int i = 0 ; i < 4 ; i++ )
   carWheels[i] = new Wheel(4);

你似乎很困惑()[] ,我建议你研究一下。

你知道ptrSize = new int(30); 不创建数组,对吗?

像C一样,你需要通过分配来获取数组的元素数。

在某些情况下,此信息实际上由实现存储,但不是以您可以访问的方式存储。

在C ++中,我们支持std :: vector和std :: array等类型。


其他说明:

ptrSize = new int(30); << creates one int with a value of 30

我该怎么做呢? Wheel(int s,int p)

通常,如果您有现有元素,则只需使用赋值:

wheelsArray[0] = Wheel(1, 2);

因为使用非默认构造函数创建数组会遇到困难。

当我们在它的时候:

std::vector<Wheel> wheels(4, Wheel(1, 2));

如果你使用矢量,只需要创建4个轮子 - 没有new要求。 不需要delete 加上,矢量知道它的大小。

暂无
暂无

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

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