【发布时间】:2016-08-18 08:59:09
【问题描述】:
假设我有以下(C++)
class Parent
{
Parent(Foo f){};
}
class Child : public Parent
{
Child(Foo f, Bar b)
: Parent(f)
{};
}
...
// And a whole bunch of other children, all calling Parent constructor
假设现在我需要向 Parent 构造函数添加一个新参数
Parent(Foo f, Baz z){};
然后我将不得不将每个子类更改为以下内容
Child(Foo f, Baz z, Bar b)
: Parent(f, z)
{};
无论如何我可以避免更改每个子类吗?
猜测可能与此有关, how to avoid repetitive constructor in children 这表明我必须更改每个子类。
如果是这样,是否有任何语言/设计模式可以让这种改变不那么痛苦?
【问题讨论】:
-
子类是否以任何方式使用新参数?如果没有,则让父级有两个构造函数。
-
如果您有这么多子类,这实际上是一件苦差事,那么您很有可能应该重新考虑您的设计。
标签: c++ inheritance design-patterns constructor