2

我正在尝试在 OpenGL 中制作游戏并想移动相机。我已经使用以下代码完成了它:

t.calculations(&t1, 5.54, 1.54, 10, 10, 1);
t.calculations(&t2, 5.54, 1.54, 10, 10, 1);
t.calculations(&t3, 5.54, 1.54, 10, 10, 1);
t.calculations(&t4, 5.54, 1.54, 10, 10, 1);
t.calculations(&t5, 5.54, 1.54, 10, 10, 1);
t.calculations(&t6, 5.54, 1.54, 10, 10, 1);
t.calculations(&t7, 5.54, 1.54, 10, 10, 1);

t.calculations(&t8, 5.54, 1.54, 10, 10, 1);
t.calculations(&t9, 5.54, 1.54, 10, 10, 1);
t.calculations(&t10, 5.54, 1.54, 10, 10 ,1);
t.calculations(&t11, 5.54, 1.54, 10, 10, 1);
t.calculations(&t12, 5.54, 1.54, 10, 10, 1);
t.calculations(&t13, 5.54, 1.54, 10, 10, 1);
t.calculations(&t14, 5.54, 1.54, 10, 10, 1);
t.calculations(&t15, 5.54, 1.54, 10, 10, 1);
t.calculations(&t16, 5.54, 1.54, 10, 10, 1);
t.calculations(&t17, 5.54, 1.54, 10, 10, 1);
t.calculations(&t18, 5.54, 1.54, 10, 10, 1);

但是正如你所看到的,这看起来像是代码的过度重复。我曾尝试使用以下方法而不是上述方法:

for (int i = 1; i < 19; i++) {
   t.calculations(&t+i, 5.54, 1.54, 10, 10, 1);
}

但它不起作用。谁能告诉我一个替代解决方案?

4

1 回答 1

2

假设 t i个变量都是同一类型且类型为 double:

// The following sentence declares an array initialized with the 18 t variables
// think of this array as a slot container of values, the following is just syntax
// to declare and initialize the array 
// IMPORTANT: Once the array is initialized, you can't modify its structure, you can 
// replace the content of every cell, but, you can add neither remove elements from it
double t[] = { t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18 };

// Then, you can read every cell of the array using the [] operator like this:
// (Another important hint, arrays starts from '0')
for (int 0 = 1; i < 18; i++) {
   // You take the address of every ti variable stored in each "cell" of the array 
   t.calculations(&t[i], 5.54, 1.54, 10, 10, 1);
}

或者,使用不那么冗长的语法(但相当复杂),上面的代码可以表示为:

for (int i = 0; i < 18; i++) {
   t.calculations(t + i, 5.54, 1.54, 10, 10, 1);
}

有关更多信息,请查看 c/c++ 中数组的在线文档和教程。类似的语法在其他语言中广泛使用

于 2012-12-24T02:15:31.140 回答