0

I have a simple class called tire. Now I want to dynamically allocate the number of tires for a vehicle when a vehicle object is created. For this, I want to create an array of tire-class objects with size equal to the number of tires. To check my code, I would like to print the number of objects in the tire-class array.

The question is: Is there a function which can check how many elements are in my tire class array? Can I use the sizeof() function?

Here is the code:

#include <iostream>

// create a class for the tires:
class TireClass {
public:
    float * profileDepths;
};

// create class for the vehicle
class vehicle {
public:
    int numberOfTires;
    TireClass * tires;
    int allocateTires();
};

// method to allocate array of tire-objects
int vehicle::allocateTires() {
    tires = new TireClass[numberOfTires];

    return 0;
};

// main function
int main() {
    vehicle audi;
    audi.numberOfTires = 4;
    audi.allocateTires();

    // check if the correct number of tires has been allocated
    printf("The car has %d tires.", sizeof(audi.tires));

    // free space
    delete [] audi.tires;

    return 0;
};
4

2 回答 2

3

不,没有。考虑使用std::vector. 或者只是将轮胎数量存储在其他变量中(也许numberOfTires足够好?)。

于 2013-10-24T08:04:43.120 回答
1

那么,当你运行代码时会发生什么?如果您在 32 位或 64 位模式下编译,它会改变吗?

发生的事情是您要求编译器告诉您保存tires变量所需的存储大小(以字节为单位)。这个变量有 type TyreClass*,所以存储大小是数据指针所需的大小:这可能是任何东西,但今天它可能是 32 位系统的 4 个字节,或 64 位系统的 8 个字节。

虽然可以sizeof用来告诉您静态分配的数组的大小,但不能用于动态(堆)分配。sizeof运算符(至少在 C++ 中)在编译时工作,而动态分配内存是在程序运行时完成的。

出于各种原因,更好的是使用 astd::vector<TyreClass>来固定轮胎。然后,您可以轻松获取存储的轮胎数量,而不必担心自己分配或取消分配数组。

(编辑:Gah,请原谅我混淆了轮胎/轮胎的英语/美国拼写。现在很晚了,我累了。)

于 2013-10-24T08:15:01.347 回答