是否可以在 C++ 中在运行时构建变量名?

Is it possible to build variable name at runtime in C++?

我有以有序方式命名的变量,i1、i2、i3,...我正在尝试使用变量名称的数字部分在运行时访问这些变量。

以下是我尝试用于解决此问题的代码。它无法正常工作。

#include <iostream>
using namespace std;

#define CreateVariable(c,v) c##v

int main()
{
    int i1(11), i2(22), i3(33), i4(44), i5(55);
    cout << CreateVariable(i, 3) << endl;   // This is working and prints "33"

    int k;
    cin >> k;                           // suppose user input '5'
    if (k > 0 && k < 6)
        cout << CreateVariable(i, k) << endl;  // This is not working

    return 0;
}

是否可以在 C++ 中实现?

不,这不可能。但是,您可以将这些 variables/values 放入数组(或映射)中并通过索引访问它们。

预处理器在编译器之前完成它的工作。 所以#define可以作为编译前的宏使用。 但是,在 C++ 中无法以这种方式在 运行 时求值。

您可以改用 STL 容器,例如 std::vectorstd::array

例如:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    std::vector<int> vec {11,22,33,44,55,66};

    int k;
    cin >> k;                           // suppose user input '5'
    if (k > 0 && k < 6)
        cout << vec[k] << endl; 

    return 0;
}