0

As all private and public attributes and methods are inherited into a child class from its parent class then why would constructors and destructors be inherited into a child class?

Is there a real life scnario?

4

1 回答 1

1

在大多数编程语言中,构造函数和析构函数不是自动继承的。通常基类可以提供一组构造函数,子类可以提供另一组构造函数。

我认为在大多数情况下抽象派生类应该提供与基类相同的构造函数集(即从基类“继承”构造函数),但具体派生类可以解析一些基类的构造函数参数并提供更多可用的集合构造函数:

考虑以下情况。假设我们有一个名为 BaseWCFProxy 的基类,它需要字符串作为端点名称:

abstract class BaseWCFProxy 
{
  public BaseWCFProxy(string endpointName)
  {}
}

class ConcreteProxy : BaseWCFProxy
{
  public ConcreteProxy() : base("ConcreteProxyEndPoint") {}
}

但是您决定在 BaseProxy 和 ConcreteProxy 之间添加额外的抽象类,而不是提供与基类相同的构造函数集:

类 DualChannelBaseProxy : BaseWCFProxy { public DualChannelBaseProxy(string enpointName) : base(endpointName) {} }

所以经验法则是:如果你写一个抽象的孩子,你应该考虑“继承”所有基类的构造函数。如果您编写一个具体的孩子,您可以提供适合您的客户的单独的构造函数集。

PS 我们对析构函数没有同样的问题,因为没有像析构函数重载这样的概念。它们是默认继承的:即后代可以提供一些额外的逻辑,但它绝对应该调用基本版本。

于 2012-11-26T11:17:31.063 回答