2012-08-27 30 views
0

如果我在堆上声明数组,我如何获得有关数组的信息?堆上的C++数组

这里是我的代码:

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(int s, int p) 

我该怎么办呢?

+1

不要使用原始数组,他们不是C++中的头等公民。改为使用'std :: array'或'std :: vector'。你会为自己节省很多麻烦。 – Fiktik

+1

请注意,您需要遵循** [Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree)**您的'Wheel'类。 –

回答

2
Wheel *carWheels[4]; 

是指针轮的数组,所以你需要用新的初始化它:

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的。如果有的话会发生,你会留在内存泄漏 -

与数组指针裸你必须记住,在某些时候删除它们,数组也不会保护你免受异常

也。

+0

当传递给函数时,'carWheels'失去大小信息,所以你最后的表达式不起作用。如果它没有通过,那就没有意义了,因为你已经知道了它的大小。 –

+0

为什么使用' - ''而不是'。'? –

+0

@Darryl因为'carWheels [0]'是指向'Wheel'的指针。它就像你有'Wheel * myWheel = new Wheel();'一样,那么你可以说'myWheel-> getPressuire();'或'(* myWheel).getPressure();'。 ' - >'只是提高了可读性。 – Fiktik

0

简单,

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

更换

Wheel *carWheels[4]; 

你似乎是混乱和()[],我建议你看个明白。

你知道ptrSize = new int(30);没有创建一个数组,对不对?

0

与C一样,您需要在分配时使用数组的元素数。

这个信息实际上是由执行存储在某些情况下,而不是在某种程度上这是你访问。

在C++中,我们倾向于使用类型,如std :: vector和std :: array。


其他说明:

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

我该怎么办呢? 轮(int类型,INT P)

通常情况下,你只需使用赋值,如果你有一个现有的元素:

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

,因为你将面临困难,创造了非默认构造函数的数组。

,虽然我们是在它:

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

是所有需要,如果你使用矢量创建4个轮子 - 没有new需要。否需要delete。另外,矢量知道它的大小。