我在初始化结构数组时遇到问题。下面是代码:
#include <iostream>
#include <array>
#include <string>
#define NUM_ELEMENT 5
struct Person
{
std::string m_name;
int m_age = 0;
Person() = default;
Person(std::string name, int age)
: m_name(name), m_age(age) {}
};
typedef std::array<Person, NUM_ELEMENT> PersonList;
class Detail
{
public:
void InitializePerson();
private:
PersonList personList;
};
void Detail::InitializePerson()
{
personList{ // <------ Getting Error here..
Person("abc", 10),
Person("cde", 20),
Person("pqr", 30),
Person("xyz", 40),
Person("apple", 50),
};
}
int main()
{
Detail detail;
detail.InitializePerson();
return 0;
}
虽然,我知道我可以将 std::vector 与 push_back
一起使用,但我想通过静态数组来实现这一点,因为它的元素是固定的。我想使用上述类 Detail 成员初始化数组,并且由于数据可以是随机的,因此无法在 for 循环
中通过 personList[0] = Person{};
最佳答案
您正在尝试初始化 personList
,这只能在构造时完成 - 但 personList
已经构造完毕,因此不起作用。您应该分配:
personList = {
Person("abc", 10),
Person("cde", 20),
Person("pqr", 30),
Person("xyz", 40),
Person("apple", 50),
};
或者:
personList = {{
{"abc", 10},
{"cde", 20},
{"pqr", 30},
{"xyz", 40},
{"apple", 50},
}};
如果您希望对其进行初始化,您可以在 Detail
构造函数中执行此操作:
class Detail {
public:
Detail() :
personList{{
{"abc", 10},
{"cde", 20},
{"pqr", 30},
{"xyz", 40},
{"apple", 50},
}}
{}
private:
PersonList personList;
};
关于c++ - 在C++11中初始化结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68343114/