【发布时间】:2011-11-18 08:33:35
【问题描述】:
考虑下面给出的代码:
struct Person{
enum sex{male,female};
int salary;
};
struct PersonSSN:public Person{
int ssn;
};
我有一个容器,其中仅包含 Person 或 PersonSSN,(在编译时已知)按工资值的升序排序。我必须编写一个函数 myfunc() 来执行以下操作。
void myfunc(){
if the container contains Person:
print the number of females between two consecutive males.
else if the container contains PersonSSN:
print the number of females between two consecutive males
and
the ssn of the males.
}
我有两个解决这个问题的方法,但都有一些缺点。
解决方案 1:如果我编写一个用于打印男性之间女性数量的函数和另一个用于打印 ssn 的函数,我必须对数据进行两次迭代,这很昂贵。
解决方案 2:我可以编写两个类,Myfunc 和 MyfuncSSN 派生自 Myfunc,并具有一个虚函数 process()。但是随后必须将打印女性数量的代码段从Myfunc 类的process() 方法复制到MyfuncSSN 类中。这里没有代码重用。
什么是更好的解决方案?
【问题讨论】:
-
bool sex??哪个是true? (为什么不使用enum,这才是真正的评论。) -
个人有 SSN。因此将
PersonSSN设计为一个单独的类是一个糟糕的设计。相反,SSN 应该作为Person本身的成员变量,IMO。只有当两个类之间存在 is 关系时,才会出现继承。 -
@Mahesh 让我们假设
Person结构已经存在。所以你建议应该修改Person结构以添加另一个数据成员而不是派生一个新结构?我在想修改现有代码可能不是一个好主意。
标签: c++ oop code-reuse