我在初始化结构数组时遇到问题。下面是代码:
#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
但我想通过静态数组实现这一点,因为它的元素是固定的。我要初始化与上面的类细节成员阵列,因为数据可以是随机的,所以不能够做到for loop
的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;
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句