我试图通过删除重复的代码来改进现有的 C++ 代码,但无法提出令人信服的方法。非常感谢更有经验的 C++ 同事的任何见解。
所以我有两个我无法控制的结构定义:
struct struct_1
{
...
other_s * s1;
other_s * s2;
other_s * s3;
... //other fields
};
struct struct_2
{
...
other_s * s1;
other_s * s2;
other_s * s3;
... //other fields, different than struct_1, but not that important
};
最后是我想要改进的代码。我有两个几乎相同的类,它们以相同的方式对同名的结构字段进行操作,但这些字段来自不同的结构。这些类不对仅存在于一个结构中的结构字段进行操作。在这里(简化):
class class_1
{
struct_1 * s;
class_1(){
s = new struct_1(); //the only practical difference
...
}
void method()
{
...
//this is simplification, in reality the code is more complex
//however the same as in class_2
inner_data += s->s1;
inner_data += s->s2;
inner_data += s->s3;
...
}
//other methods
};
class class_2
{
struct_2 * s;
class_2(){
s = new struct_2(); //the only practical difference
...
}
void method()
{
...
//this is simplification, in reality the code is more complex
//however the same as in class_1
inner_data += s->s1;
inner_data += s->s2;
inner_data += s->s3;
...
}
//other methods
};
我花了一些时间试图重做它,但最终无处可去。我的方法是只使用一个类 class_1,但我无法避免在没有多个 if 分散的情况下访问 struct_1 和 struct_2 的问题。感谢您的帮助!