如何避免C++11中收缩转换的错误
How to avoid error of narrowing conversion in c++11
我有下面的代码,它使用枚举值来初始化结构的向量。
我收到有关窄转换的错误。我参考了 Microsoft 文档: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;
}
因为我们可以看到上面带有类型转换的 vector 初始化看起来 weird/complex。我怎样才能提高代码的可读性。我试过下面的代码,但它抛出 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"}
};
*/
您可以定义一个用于枚举的类型,这样就不需要强制转换了:
enum NUMBERS : uint32_t
{
NUMBERS_ZERO = 0xA0000000,
NUMBERS_ONE = 0xA0000001,
NUMBERS_TWO = 0xA0000002,
NUMBERS_THREE = 0xA0000003,
};
如果没有类型定义,可以假定数字是有符号的并且不适合 32 位整数,因此使用缩小转换。
我有下面的代码,它使用枚举值来初始化结构的向量。 我收到有关窄转换的错误。我参考了 Microsoft 文档: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;
}
因为我们可以看到上面带有类型转换的 vector 初始化看起来 weird/complex。我怎样才能提高代码的可读性。我试过下面的代码,但它抛出 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"}
};
*/
您可以定义一个用于枚举的类型,这样就不需要强制转换了:
enum NUMBERS : uint32_t
{
NUMBERS_ZERO = 0xA0000000,
NUMBERS_ONE = 0xA0000001,
NUMBERS_TWO = 0xA0000002,
NUMBERS_THREE = 0xA0000003,
};
如果没有类型定义,可以假定数字是有符号的并且不适合 32 位整数,因此使用缩小转换。