现在的位置: 首页 > 综合 > 正文

第四章:继承–4.2.6 派生类的构造函数

2012年02月15日 ⁄ 综合 ⁄ 共 2247字 ⁄ 字号 评论关闭

注:此文讨论范围仅限于构造函数的执行情况,不涉及类的设计问题

 

1. 构造函数的调用顺序

    实例化一个类时,总是先调用System.Object,再按类的继承照层次结构由上向下进行,直到到达编译器要实例化的类为止。

    例如:

代码:实例化派生类时,构造函数的执行顺序

using System;

namespace Constructor
{
class Program
{
static void Main(string[] args)
{
Bueaty fang
= new Bueaty();
Console.Read();
}
}

class Human //基类
{
public Human () //基类构造函数
{
Console.WriteLine(
"base....");
}
}

class Bueaty:Human //派生类
{
public Bueaty() //派生类构造函数
{
Console.WriteLine(
"inherit..");
}
}
}

那么运行结果是:

base....
inherit..

当然,在执行Human类的构造函数之前,还执行了Object类的构造函数,只是这里没法显示。

 

2. 可以在执行一个构造函数之前,显式地调用其基类的构造函数,如在Bueaty类的构造函数中:

public Bueaty() //派生类构造函数
:
base()
{
Console.WriteLine(
"inherit..");
}

 如果编译器没有在当前类的构造函数之前找到对另一个构造函数的调用,则会默认我们调用基类的构造函数。

除了是用“:base()”调用基类的构造函数,还可以使用“:this()”调用当前类的重载构造函数,同时,这两者都可以带参数。

 

 

3. 如果一个类定义了带参的构造函数,则不会产生默认的构造函数(默认的构造函数是没有参数的),所以,如果代码写成了以下的样子:

代码:由于基类没有默认构造函数而导致的错误

using System;

namespace Constructor
{
class Program
{
static void Main(string[] args)
{
Bueaty fang
= new Bueaty(20);
Console.Read();
}
}

class Human //基类
{
public Human (int height) //基类构造函数
{
Console.WriteLine(
"base....");
Console.WriteLine(
"Height is "+height);
}
}

class Bueaty:Human //派生类
{
public Bueaty(int age) //派生类构造函数
{
Console.WriteLine(
"inherit..");
Console.WriteLine(
"Age is "+age);
}
}
}

 

 

VS会报错:

Error 1 'Constructor.Human' does not contain a constructor that takes '0' arguments D:\Study\Constructor\Constructor\Program.cs 24 15 Constructor
双击错误,被高亮显示的却是Bueaty类的构造函数,原来,由于Bueaty类的构造函数没有调用其基类Human类的构造函数,编译器会默认调用Human类的无参

的构造函数(如前文第2点所述),而Human类已经定义了一个有参数的构造函数public Human (int height),这样便不会再提供默认的无参构造函数,因此其

派生类Bueaty便无法实例化。

解决的办法是在Human类中自己定义一个无参的构造函数,该函数什么都不用干:

代码:添加一个无参的构造函数

class Human //基类
{
public Human() //基类无参构造函数
{ }
public Human (int height) //基类有参构造函数
{
Console.WriteLine(
"base....");
Console.WriteLine(
"Height is "+height);
}
}

运行结果:

inherit..
Age is 20

4. 当然,并不是说基类一定要加这个无参的构造函数,例如,如果在派生类中显式地调用基类中的有参构造函数,那么基类的无参构造函数就不会被调用。

例如:

代码:基类没有无参构造函数的情况
using System;

namespace Constructor
{
class Program
{
static void Main(string[] args)
{
Bueaty fang
= new Bueaty(20,165); //传递两个参数,实例化一个对象
Console.Read();
}
}

class Human //基类
{
public Human (int height) //基类有参构造函数
{
Console.WriteLine(
"base....");
Console.WriteLine(
"Height is "+height);
}
}

class Bueaty:Human //派生类
{
public Bueaty(int age,int height) //派生类构造函数
:base(height) //传递一个参数给基类构造函数
{
Console.WriteLine(
"inherit..");
Console.WriteLine(
"Age is "+age);
}
}
}

输出结果:

base....
Height is 165
inherit..
Age is 20

某某人为实现自己每天至少一篇技术blog的诺言,周末晚上在公司写blog,精神可嘉... ...

 

抱歉!评论已关闭.