【发布时间】:2021-07-20 05:45:14
【问题描述】:
我有下面的代码,它使用枚举值来初始化结构的向量。 我收到有关窄转换的错误。我已经推荐了微软文档:link 我可以通过以下代码解决问题。
#include <iostream>
#include <vector>
#include <string>
enum NUMBERS
{
NUMBERS_ZERO = 0xA0000000,
NUMBERS_ONE = 0xA0000001,
NUMBERS_TWO = 0xA0000002,
NUMBERS_THREE = 0xA0000003,
};
struct Person {
uint32_t m_id = 0;
std::string m_name;
Person(uint32_t id, std::string name) :
m_id(id), m_name(name) {}
};
std::vector<Person> PersonList =
{
{static_cast<uint32_t>(NUMBERS_ZERO), "abc"},
{static_cast<uint32_t>(NUMBERS_ONE), "pqr"},
{static_cast<uint32_t>(NUMBERS_TWO), "xyz"},
{static_cast<uint32_t>(NUMBERS_THREE), "zzz"}
};
int main()
{
for (auto it : PersonList)
std::cout << it.m_id << " : " << it.m_name << "\n";
return 0;
}
因为我们可以看到上面带有类型转换的向量初始化看起来很奇怪/复杂。如何以更具可读性的方式改进代码。我已经尝试了下面的代码,但它会抛出 error: Conversion from 'Numbers' to 'uint32_t' requires a narrow conversion. 任何建议将不胜感激。
/*
struct Person {
uint32_t m_id = 0;
std::string m_name;
Person(uint32_t id, std::string name) :
m_id(static_cast<uint32_t>(id)), m_name(name) {}
};
std::vector<Person> PersonList =
{
{NUMBERS_ZERO, "abc"},
{NUMBERS_ONE, "pqr"},
{NUMBERS_TWO, "xyz"},
{NUMBERS_THREE, "zzz"}
};
*/
【问题讨论】:
-
对于这段代码 sn-p,我会删除
enum并只定义这些值:const uint32_t NUMBERS_ZERO = 0xA0000000;等。当然,在现实世界中,可能需要一个实际enum.
标签: c++ c++11 initializer-list