[英]C++ Macro to use values of variables
I have a program with 4 objects of a class, say PO1, PO2, PO3, PO4. 我有一个带有4个类的对象的程序,例如PO1,PO2,PO3,PO4。 I want to call some functions taking these objects as parameters in a for loop.
我想调用一些函数,将这些对象作为for循环中的参数。 Like so:
像这样:
for(int i = 0; i < 4; i++){
func(PO<i>); //Something like a macro to replace the value i in the function.
I tried token pasting, but all I got was POi, instead of getting the value of i. 我尝试了令牌粘贴,但是我得到的只是POi,而不是获得i的值。 Is there any way to do this?
有什么办法吗? (Macro, Function, etc.)
(宏,功能等)
Here's my code 这是我的代码
Player PO[4] = {Player{'l',WHITE},
Player{'l',WHITE},
Player{'l',WHITE},
Player{'l',WHITE}
};
'l' and WHITE are the parameters. 参数“ l”和“ WHITE”。
Based on @SamVarshavchik's comment, I got a solution. 根据@SamVarshavchik的评论,我找到了解决方案。
Here it is, 这里是,
Player *PK[4] = {&PO1,&PO2,&PO3,&PO4};
for(int i = 0; i < 4; i++}{
func(*PK[i]);
}
Use array or std::vector
instead 使用array或
std::vector
代替
MyObject Pos[4] = {MyObject{42}, MyObject{51}, MyObject{21}, MyObject{12}};
for (auto& po : Pos) {
func(Po);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.