我有以下枚举(后来会变大!):
enum TrainingFilters {
NONE = 0,
GAUSS = 1,
SOBEL = 2,
FEATURE = 4
};
我必须打印出所有可能组合的字符串表示。现在,一个not-leangthy开关语句工作正常,但如果我添加更多项目,那将是灾难!
void Manager::setFilters(int filters)
{
QString what("Selected filters:");
switch (filters) {
case 0:
what.append(" NONE ");
break;
case 1:
what.append(" GAUSS ");
break;
case 1 | 2:
what.append(" GAUSS SOBEL ");
break;
case 2:
what.append(" SOBEL ");
break;
case 2 | 4:
what.append(" SOBEL FEATURE ");
break;
case 4:
what.append(" FEATURE ");
break;
case 1 | 4:
what.append(" GAUSS FEATURE ");
break;
case 1 | 2 | 4:
what.append(" GAUSS SOBEL FEATURE ");
break;
default:
qDebug() << "Invalid FILTERS enum received!";
return;
}
qDebug() << what;
mFilters = static_cast<TrainingFilters>(filters);
}
P.S:我在用户界面中有几个复选框项,我应该根据选中的复选框做一些事情。我这样用它:
var a, b,c;
cbGauss.checked ? a = 1 : a = 0;
cbSobel.checked ? b = 2 : b = 0;
cbFeat.checked ? c = 4 : c = 0;
cpManager.setFilters(a | b | c);
所以我的qustion是实现这个目标的最佳/最简单/最聪明的方法吗?
答案 0 :(得分:1)
你可以简单地做
if (filters & 1)
what.append("GAUSS ");
if (filters & 2)
what.append("SOBEL ");
if (filters & 4)
what.append("FILTER ");
等等。这样您就可以轻松添加新的。当然你必须检查零,然后添加NONE。