在C ++中,如何迭代到达名称仅因数字而异的几个变量? [英] How to reach iteratively few variables which names differ only by number in C++?

查看:100
本文介绍了在C ++中,如何迭代到达名称仅因数字而异的几个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来帮助我,使每个变量在一个循环中分别到达名为"comboBox1","comboBox2"等的变量.我想更改以下代码:

I need a method helping me, to reach variables named like "comboBox1", "comboBox2" etc each by each in a loop. I'd like to change code like:

//proceed comboBox1
//proceed comboBox2
//proceed comboBox3
//proceed comboBox4
//proceed comboBox5
//proceed comboBox6

进入:

for (int i = 1; i < numberOfBoxes; i++) {
    //proceed comboBox(i)
}

我试图找到类似"eval"的东西,但是google没有给出任何匹配的东西.我还尝试使用运算符##预处理名称,但似乎无法将当前整数值放入宏.

I tried to find somthing like 'eval', but google didn't give anything matching. I also tried preprocessing the name with operator ## but it seems there's no way to put current integer value to the macro.

推荐答案

最简单的解决方案是将它们全部放入数组中,并在其上进行迭代:

The simplest solution is to put them all in an array and iterator over that:

// I've made up a type, but you get the idea.
std::vector<ComboBox *> combos;
combos.insert(comboBox1);
combos.insert(comboBox2);
combos.insert(comboBox3);
combos.insert(comboBox4);
combos.insert(comboBox5);
combos.insert(comboBox6);

现在您可以遍历连击.主要问题是c ++没有反射.因此,您无法在运行时生成字符串并像其他语言一样获取对象或函数的地址.

Now you can iterate over combos. The main problem is that c++ doesn't have reflection. So you can't generated a string at runtime and get the address of an object or function like you can in some other languages.

我刚刚看到您正在使用Qt.在这种情况下,您应该使用:

I just saw that you are using Qt. In that case, you should use:

QList<T> qFindChildren ( const QObject * obj, const QString & name );

QList<T> qFindChildren ( const QObject * obj, const QRegExp & regExp);

这使您根据运行时生成的名称获取列表.例如:

QList<QComboBox *> combos = qFindChildren(ui, QRegExp("combo[0-9]+"));

那您就可以遍历了!

这篇关于在C ++中,如何迭代到达名称仅因数字而异的几个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆