Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

class - c++ storing an object into an array of objects within the constructor of that object

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...