首页 > 解决方案 > 有没有办法优化/减少这个分配变量的顺序?(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);
}

标签: c++reduce

解决方案


使用初始化列表:

#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;
}

推荐阅读