【C++日常】C++动态命名变量名

原文链接在这:http://blog.sina.com.cn/s/blog_6a8766400100uh3v.html

需求就是因为需要动态改变变量的名称,检索到这个,做一个记录:

#include <stdio.h>
#define SET_NAME(name) test##name

int main()
{
    int SET_NAME(1) = 1212;
    printf("%d
",test1);
    return 0;
}

但是,需要注意的是,作为一种静态语言,在c++里面你不能使用还没有创建的变量,即如下这种操作:

#include<stdio.h>
#define SET_NAME(name) test##name
int main()
{
    for (int i = 0; i<5;i++)
    {
        int SET_NAME(i) = i;
        printf("%d
",testi);
    }
//以上都是正确的,可以正常输出的,但是接下来的操作是不可以的,因为你试图操作一个还没有定义的变量
//,即使在for的作用域里面也不行,因为test1是在程序运行过程中才定义的
    printf("%d
",test1);
}

那怎么办呢?最后做了点变通,然后定义vector直接pushback




原文地址:https://www.cnblogs.com/portb/p/12037327.html