OOP继承和默认构造函数 [英] OOP inheritance and default constructor

查看:151
本文介绍了OOP继承和默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个基类 A 和一个 B 类派生自 A
然后,我们知道类 A 的构造函数不会被类 B 继承。但是,当创建 B 的新对象时, - A 的默认构造函数在将调用 B 类的默认/自定义构造函数。也许这样做的目的是将 A 的字段需要初始化为默认值。



假设 A 类定义了一个自定义构造函数。这意味着 A 的默认构造函数由编译器静默删除。现在,在创建类 B 的新实例时,会调用 A 类的构造函数, code> B 的构造函数? (在这种情况下,如何初始化 A 字段?)

解决方案


现在,在创建 B 类的新实例 A 在调用 B 构造函数之前自动调用


将无法编译,基本上。每个构造函数必须链接到另一个构造函数,隐式或显式。它链接的构造函数可以在同一个类中( this )或基类( base )。



这样的构造函数:

  public B 

是隐含的:

  public B():base(){} 

...你根本不指定构造函数,它将以相同的方式隐式添加 - 但它仍然需要调用一些东西。例如,您的方案:

  public class A 
{
public A(int x){ }
}

public class B:A {}

导致编译器错误:


错误CS7036:没有参数对应于所需的形式参数 'x' of 'AA(int)'


但是,您可以明确指定不同的构造函数调用,例如

  public B //链接到基类构造函数

  public B():this(10){} //链接到同一个类构造函数,假设存在


Suppose there is a base class A and a class B derived from A. Then, we know that the constructor of class A is never inherited by class B. However, when a new object of B is created, then - the default constructor of the class A is called prior to the default/custom constructor of class B is invoked. Maybe the purpose of this is that the fields of class A need to be initialized to default values.

Now, suppose that class A has defined a custom constructor. This means that the default constructor of class A is silently removed by the compiler. Now, on creating a new instance of class B, which constructor of class A is automatically called before invoking the class B's constructor? (How does the class A fields get initialized in such a case?)

解决方案

Now, on creating a new instance of class B, which constructor of class A is automatically called before invoking the class B constructor?

The code will fail to compile, basically. Each constructor has to chain to another constructor, either implicitly or explicitly. The constructor it chains to can be in the same class (with this) or the base class (with base).

A constructor like this:

public B() {}

is implicitly:

public B() : base() {}

... and if you don't specify a constructor at all, it will be implicitly added in the same way - but it still has to have something to call. So for example, your scenario:

public class A
{
    public A(int x) {}
}

public class B : A {}

leads to a compiler error of:

error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'A.A(int)'

However, you can specify a different constructor call explicitly, e.g.

public B() : base(10) {} // Chain to base class constructor

or

public B() : this(10) {} // Chain to same class constructor, assuming one exists

这篇关于OOP继承和默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆