简体   繁体   English

c++ - 将对象设置为指向对象类的指针数组

[英]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:我有一个类名 MyDate 具有以下成员和方法:

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.我有另一个类名 Calendar,它有一个指向 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;我知道我不能做*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??有没有办法在没有 MyDate 类的 getter 的情况下实现它?

You can't use *m_dates[f]=my_date;你不能使用*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));如果您可以并且想要使用智能指针数组( std::array<std::shared_ptr<MyDate>, 30> m_dates; ),您可以使用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.首先,您的数组保持指向 mydate 对象的指针,您必须正确管理数据。 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.如果我查看用于 insertDate 的接口,insertDate(myDate *my_date) 就很清楚了,您可以简单地使用 m_dates[f]=my_date 将值设置为数组。 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.如果您打算保留指针,您可能必须确保在程序和 myData 对象期间设置有效的指针得到正确管理。 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.正如在 C++11 中的一条评论中提到的,您可以利用 shared_pointers 这样您就不必显式管理内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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