【问题标题】:How to add newly created object into array如何将新创建的对象添加到数组中
【发布时间】:2021-03-28 17:50:54
【问题描述】:

我想将一个对象添加到数组中。我试图在这个的构造函数中做到这一点。我开始学习 c++,但我不确定为什么它不能以这种方式工作。有人可以解释为什么它不起作用以及如何正确地做到这一点吗?

#include <iostream>

using namespace std;

const int CAPACITY = 50;

class Photo
{
    private:
        string title, description, size;
        int year, month;
        static Photo collection[CAPACITY];
        static int collection_size;

    public: 
        Photo(string title, string description, string size, int year, int month)
            :title(title), description(description), size(size), year(year), month(month)
        {
            collection[collection_size++] = this;
        }

        Photo()
            :Photo("", "", "1920x1080", 2021, 1)
        {
        }

        static int get_collection_size(){
            return collection_size+1;
        }

        static void print_collection(){
            for(auto photo : collection){
                cout << photo.size;
            }
        }
};

Photo Photo::collection[CAPACITY] = {};
int Photo::collection_size = 0;


int main(){
    Photo p;
    p.print_collection();
    return 0;
}

【问题讨论】:

  • 不是答案,但我强烈建议您查看参考资料 (&amp;)

标签: c++


【解决方案1】:

您的构造函数试图将Photo* 指针存储到Photo 对象数组中。你必须要么

  • 取消引用this 指针以分配被指向的Photo 对象。

collection[collection_size++] = *this;

  • 更改数组以存储Photo* 指针。

static Photo* collection[CAPACITY];

【讨论】:

    【解决方案2】:

    您不能在 Photo 类中定义 static Photo collection[CAPACITY];。您可能应该为单张照片创建一个类或结构(即,没有集合,只有一个),然后在其他地方创建一个数组,或者可能是另一个类来保存和管理集合。 您可能还想看看标准容器。 https://en.cppreference.com/w/cpp/container

    编辑:代码示例

    class Photo
    {
        std::string title, description, size;
        int year, month;
        ...
    };
    
    static Photo static_photo_collection[50];
    

    或许

    class Photo
    {
        std::string title, description, size;
        int year, month;
        ...
    };
    
    class Photo_Collection
    {
        Photo collection[50];
        ...
        // Constructor, destructor if you want
        // functions to add, remove, somehow manage the collection
    };
    
    // if you really wanted a static collection...
    static Photo_Collection my_photo_collection;
    

    【讨论】:

    • 为什么不能在类中定义static Photo collection[CAPACITY]?你绝对可以——这不是问题。也不需要单独的类/结构...
    • @ChrisMM 我几乎可以肯定编译器会抱怨不完整的类定义什么的,因为它还没有到达类定义的末尾(所以它无法知道类的大小创建数组)
    • 自我引用不是这样的,不。请参阅 Remy 的回答以了解问题所在。
    猜你喜欢
    • 2021-04-18
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2020-09-01
    • 2022-07-28
    • 2016-01-14
    • 2022-01-16
    相关资源
    最近更新 更多