内部有结构体的Enum或数组

Enum or array with structs inside

本文关键字:数组 Enum 结构体 内部      更新时间:2023-10-16

我有这样的(常量)数据:

(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();