Since you have to use an array to keep all objects you have to define a constant maximum size, since the size of an array is fixed and cannot be changed. This means that you also have to define a variable that keeps track of how many elements the array has, so that you don't exceed its boundaries.
const int MAX_SIZE = 100;
class Rectangle
{
private:
int width;
int length;
static Rectangle* all_rectangles[MAX_SIZE];
static int rectangle_count;
public:
Rectangle();
Rectangle(int x, int y);
};
Then you define the static variable and add the objects to the array in the Rectangle constructor, for example:
//Define static variables
Rectangle* Rectangle::all_rectangles[MAX_SIZE];
int Rectangle::rectangle_count = 0;
//Constructor
Rectangle::Rectangle () {
all_rectangles[rectangle_count] = this;
rectangle_count++;
}
Since the array with rectangles (and its components) is private, you can only reach it from within the class. You can however define functions that are public, to reach the rectangles private variables. You can get the width of a rectangle by declaring a function
static int getWidth(int a){
return all_rectangles[a]->width;
}
and call it by cout << Rectangle::getWidth(2) // Get width of second element in array
However vectors are preferable to use before arrays since they are expandable and includes many build-in functions, such as add and remove elements.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…