c++ - 有没有办法优化/减少这个分配变量的顺序?(C++)
问题描述
我想知道是否有办法优化/减少这种逻辑?随着变量数量的增加,参数的数量也会增加,这会使代码有点混乱。
.h 文件
class ClassA
{
public:
ClassB type1_1;
ClassB type1_2;
ClassB type1_3;
// ... There can be more than this
ClassB type2_1;
ClassB type2_2;
ClassB type2_3;
// ... There can be more than this
void SetType1(ClassB a, ClassB b, ClassB c);
void SetType2(ClassB a, ClassB b, ClassB c);
__forceinline vector<ClassB> GetListofType1() { return list_type1; }
__forceinline vector<ClassB> GetListofType2() { return list_type2; }
private:
vector<ClassB> list_type1;
vector<ClassB> list_type2;
};
.cpp 文件
// ... As the number of type1 variables increases, the number of parameters increases
void ClassA::SetType1(ClassB a, ClassB b, ClassB c)
{
type1_1 = a;
type1_2 = b;
type1_3 = c;
list_type1.push_back(a);
list_type1.push_back(b);
list_type1.push_back(c);
}
// ... As the number of type2 variables increases, the number of parameters increases
void ClassA::SetType2(ClassB a, ClassB b, ClassB c)
{
type2_1 = a;
type2_2 = b;
type2_3 = c;
list_type2.push_back(a);
list_type2.push_back(b);
list_type2.push_back(c);
}
解决方案
使用初始化列表:
#include <cassert>
#include <vector>
struct ClassB { };
class ClassA {
public:
static constexpr int list_type1_len = 3;
inline void SetType1(const std::vector<ClassB>& set_type_1){
assert(set_type_1.size()==3);
list_type1 = set_type_1;
}
inline std::vector<ClassB>& GetListofType1() { return list_type1; }
private:
std::vector<ClassB> list_type1;
};
int main(){
ClassA a;
a.SetType1({ClassB(), ClassB(), ClassB()});
return 0;
}
推荐阅读
- php - JWPlayer 使用 php 文件而不是直接链接不起作用
- android - Crashlytics 无法初始化
- javascript - 制作一个将数字放在数组中间的函数
- css - 我正在尝试使用一个很棒的字体图标作为按钮
- sql - 如何在 Oracle SQL 输出中将行转换为表列?
- spring-boot - 我在 Jpql 中使用 @Query 注释,我用额外的“不同”修改了我的查询,如何修复它?
- algorithm - 以最高效率访问无向图中所有节点的算法?
- python - '没有这样的文件或目录' 使用“打印”时的错误信息
- selenium - 如果元素不存在,为什么测试需要比指定的时间更长的隐含等待时间失败
- amazon-web-services - 如何输出多个 S3 存储桶地址