在头文件的数组中定义资源 ID

Defining Resource ID's in an array in a header file

本文关键字:定义 资源 ID 数组 文件      更新时间:2023-10-16

我试图在头文件中以矢量格式定义RID的连续范围:

    #include<vector>
    #include<stdlib.h>
    #include<iostream>
    #define vector<int> IDM_POPUP_LAST (5);
    for(i = 0; i < IDM_POPUP_LAST.size(); i++)
    IDM_POPUP_LAST [i] = i + 90;

这里少了什么吗。我有一组错误:

您正在尝试静态初始化数据,并且希望它位于vector的对象中(如果我理解正确的话)。不幸的是,这在C++中是不可能的。然而,你还可以探索其他选择:

1) 使用静态数组,类似于以下内容:

int IDM_POPUP_LAST[] = {1, 2, 3, 4, 5};

2) 有一个向量在main()的早期初始化,或者由伪类的构造函数初始化,如下所示:

vector<int> IDM_POPUP_LAST(5);
struct DummyInitializer
{
  DummyInitializer()
  {
    // code to initialize the vector IDM_POPUP_LAST
  }
} global_var_so_the_constructor_is_called_before_main;

您的变量声明是错误的。变量通常使用以下语法声明:

std::vector<int> IDM_POPUP_LAST (5);

除此之外,for不能简单地放在函数之外。

话虽如此,这可能是一个全局变量。绕过这一点的一种方法是使它成为类的静态成员,并使用一个函数对其进行初始化。当你决定需要其他类型的id时,你甚至可以在这里添加它们,并根据需要将初始化它们添加到函数中:

//resource.h
struct ResourceIDs {
    static std::vector<int> menus;
    static void init();
    //Let's add in three cursors
    static std::vector<int> cursors;
};
//NOTE - these are all better off in a .cpp
#include "resources.h" //if in the cpp
std::vector<int> ResourceIDs::menus (5); //define the menus member
std::vector<int> ResourceIDs::cursors (3); //define the cursors member
void ResourceIDs::init() {
    for (int i = 0; i < menus.size(); ++i) //note the type mismatch since vector
        menus[i] = i + 90;                 //uses size_t, which is unsigned
    //let's do cursors starting at 150
    for (int i = 0; i < cursors.size(); ++i)
        cursors[i] = i + 150;
}

现在你只需要确保初始化它们,然后你可以在任何需要的地方使用它们:

#include <windows.h>
#include "resource.h"
int main() {
    ResourceIDs::init();
    //create window, message loop, yada yada
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {
        case WM_COMMAND:
        //check the menu ids using ResourceIDs::menus[x]
        default:
            return DefWindowProc (hwnd, msg, wParam, lParam);
    }
}    

这里与代码#定义id的样子的唯一区别是在main开始时调用ResourceIDs::init()、需要ResourceIDs::以及数组语法。