原文鏈接在這: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\n",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\n",testi);
}
//以上都是正確的,可以正常輸出的,但是接下來的操作是不可以的,因為你試圖操作一個還沒有定義的變量
//,即使在for的作用域里面也不行,因為test1是在程序運行過程中才定義的
printf("%d\n",test1);
}
那怎么辦呢?最后做了點變通,然后定義vector直接pushback
