内部有结构体的Enum或数组
Enum or array with structs inside
我有这样的(常量)数据:
(index) Width Height Scale Name
0 640 360 1 "SD"
1 1080 720 2 "HD"
2 1920 1080 3 "FHD"
到目前为止,我已经创建了这样的结构:
struct Resolution
{
int Width;
int Height;
int Scale;
std::string Name;
};
现在我需要一个对象让我可以做这样的事情:
int index = 0;
int width = Resolutions[index].Width; // 360
我需要enum或一些数组,它将是常量,并且不需要初始化(静态?)。
作为一个开始,因为它是常量数据,我不会使用std::string
。
但是我会这样做:
struct Resolution
{
int Width;
int Height;
int Scale;
const char * Name;
};
struct Resolution Resolutions[] = {
{640, 360, 1, "SD"},
{ 1080, 720, 2, "HD"},
{ 1920, 1080, 3, "FHD"}
};
但另一方面,我会使用小写的变量
如果Resolutions
中的元素不是编译时间常数,则需要std::vector
,如果它们是并且集合不需要增长,则需要std::array
。例如:
#include <array>
…
const std::array<Resolution, 3> Resolutions =
{{ /* Width Height Scale Name */
{ 640, 360, 1, "SD" },
{ 1080, 720, 2, "HD" },
{ 1920, 1080, 3, "FHD" }
}};
如果您希望索引具有有意义的名称,而不是0
, 1
, 2
,您可以创建enum
:
enum ResolutionIndex { SD, HD, FHD };
并使用它作为数组索引:
ResolutionIndex index = SD;
int width = Resolutions[index].Width;
这使得代码比现在更安全:
ResolutionIndex index = 4;
是一个无效的索引。有效的索引值硬编码在枚举中,编译器强制执行。如果您使用int
:
int index = 4;
,编译器不能帮助你,如果你给一个无效的索引。
您可以创建一个类(在c++中更好),并在您的主类中,该类的一个向量,如下所示:
class Resolution {
public:
Resolution(unsigned int, unsigned int, unsigned int, std::string const &);
~Resolution();
private:
unsigned int Width;
unsigned int Height;
unsigned int Scale;
std::string Name;
};
在你的主类中:
class MainClass {
public:
...
private:
...
std::vector<Resolution *> m_res;
};
在cpp文件中:
MainClass::MainClass() {
this->m_res.push_back(new Resolution(640, 360, 1, SD));
this->m_res.push_back(new Resolution(1080, 720, 2, HD));
this->m_res.push_back(new Resolution(1920, 1080, 3, FHD));
}
你可以这样访问一个元素(当然,你需要getter):
this->m_res[index].getValue();
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '