如何制作一个变种.带有var的名称 在C/C++中?

gur*_*gui 0 c c++ scope variable-variables

我有一些vars直播:

int foo1;
int foo2;
..
Run Code Online (Sandbox Code Playgroud)

我希望通过以下方式与他们联系:

for (int i = 1;i<=2;i++)
{
   // howto get foo1 and foo2?
}
Run Code Online (Sandbox Code Playgroud)

怎么弄他们?

编辑,结束什么时候它不是int而是一个Opject*指针;?

Oli*_*rth 7

你不能; 你需要某种阵列.例如:

int foo[2];   /* Two elements, foo[0] and foo[1] */
for (int i = 0; i < 2; i++)
{
    foo[i] = i;
}
Run Code Online (Sandbox Code Playgroud)

要么:

int foo1;
int foo2;
int *p[] = { &foo1, &foo2 };   /* Array of pointers */
for (int i = 0; i < 2; i++)
{
    *p[i] = i;   /* Changes foo1 or foo2 */
}
Run Code Online (Sandbox Code Playgroud)

我不完全理解你的最后一个问题,但如果你的意思是你想要的数据类型是Object *不是int,那么所有你需要做的是替代品Object *int进入我上面的代码示例(比其他int i = 0,很明显).