Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to create an object and everytime I create an object, I then store that object in a static class variable that is an array of all of the objects created.

I am new to c++ and have no idea how to accomplish this. I have done it in Java before, but I am stuck here.

Take this for example purposes:

class Rectangle
{
    private:
        int width;
        int length;
        // Code to create an array of Rectangle Objects 
        // that hold all the the Rectangles ever created

    public:
        Rectangle();
        Rectangle(int x, int y);
};

Rectangle::Rectangle()
{
    width = 0;
    length = 0;
    // code to add an instance of this object to an array of Rectangle Objects
}

Rectangle::Rectangle(int x, int y)
{
    width = x;
    length = y;
    // code to add an instance of this object to an array of Rectangle Objects
}

Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
712 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...