【发布时间】:2019-12-14 02:37:06
【问题描述】:
我曾经有一段代码可以提取某些部分
auto& c = m_matrix[name];
....large block of code with using c in the calculation...
现在我必须为 m_matrix 选项使用 if/else 或 switch case,如下语句:
switch input{
case 1:
auto& c = A[name];
case 2:
auto& c = B[name];
}
....large block of code with using c in the calculation...
A 和 B 具有相同类型的元素。但是,这是错误的,因为它表明 c 的定义是重复的。同时我不能声明auto&c;在 switch/case 之前以及如下所示:
auto& c;
switch input {
case 1:
c = A[name];
case 2:
c = B[name];
}
....large block of code with using c in the calculation...
有没有办法解决这个问题?
更新:CinCout - 恢复莫妮卡请提供解决方案
switch input {
case 1:{
auto& c = A[name];
....large block of code with using c in the calculation...
}
case 2:{
auto& c = B[name];
....large block of code with using c in the calculation...
}
}
有没有办法避免每种情况下的重复代码?谢谢
【问题讨论】:
-
矩阵表达式或它们的元素是否都具有相同的类型,或者类型是否不同?
-
另外,您的问题将通过语言标签获得更多关注。这看起来像 C++,除了“结束”?
-
感谢您的回复。元素都具有相同的类型。
-
“我也不能在 switch/case 之前声明 auto&c;。” 绝对不能作为 参考,但你当然可以它作为变量或指针。
-
你需要说明
A和B是如何声明的。
标签: c++ c++11 if-statement switch-statement auto