【发布时间】: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;
}
【问题讨论】:
-
不是答案,但我强烈建议您查看参考资料 (
&)
标签: c++