简体   繁体   中英

c++ - set object to array of pointers to the class of the object

I have a class name MyDate with the following members and methods:

class MyDate
{
    public:
        MyDate();
        void setDay(int d);
        void setMonth(int m);
        void setYear(int y);
        void set(int day_, int month_, int year_);
        void print ();

    private:
    int day;
    int month;
    int year;

};

I have another class names Calendar which has an array of pointers to MyDate.

class Calendar 
{
    public:
        Calendar() ;
        void setDate (int num);
        bool isFree(int num_);
        int firstFree();
        void insertDate(MyDate my_date_);

        void print ();

    private:
        std::array<MyDate*, 30> m_dates;

};

I implement the insert function in the following way:

void Calendar :: insertDate(MyDate my_date)
{
int f = firstFree()-1 ;//the first free index in the array
*m_dates[f]=my_date; //is there a way to implement it without getters from //MyDate class??
}

I know that I can't do *m_dates[f]=my_date; --->just to explain what I have to implement. is there a way to implement it without getters from MyDate class??

You can't use *m_dates[f]=my_date; because the array only has pointers, so you still need to provide storage space for the actual objects. If you can and want to use smart an array of smart pointers ( std::array<std::shared_ptr<MyDate>, 30> m_dates; ) , you can use m_dates[f].reset(new MyDate(my_date)); , otherwise you have to take care of memory management.

First of all your array is keeping the pointers to the mydate objects and you have to properly manage the data. If I look at the interface that you use to insertDate, insertDate(myDate *my_date) would have been clear and you can use simply m_dates[f]=my_date to set the values to the array. You might have to make sure the pointers which are set valid during the program and myData objects are properly managed if your intention is to keep pointers. As mentioned in one comment in C++11 you can take the advantage of shared_pointers so you do not have to manage memory explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM