构造函数

     构造函数用于执行类的实例的初始化每个类都有构造函数即使我们没有声明它编译器也会自动地为我们提供一个默认的构造函数在访问一个类的时候系统将最先执行构造函数中的语句实际上任何构造函数的执行都隐式地调用了系统提供默认的构造函数base().
     如果我们在类中声明了如下的构造函数
    C(…) {…}
  它等价于
    C(…): base() {…}
  使用构造函数请注意以下几个问题
     #一个类的构造函数通常与类名相同
     # 构造函数不声明返回类型
            # 一般地 构造函数总是public 类型的如果是private 类型的表明类不能被实例化这通常用于只含有静态成员的类
     # 在构造函数中不要做对类的实例进行初始化以外的事情也不要尝试显式地调用构造函数
  下面的例子示范了构造函数的使用:

        class A
        {
            int x = 0, y = 0, count;
            public A()
            {
                count = 0;
            }
            public A(int vx, int vy)
            {
                x = vx;
                y = vy;
            }
        }

构造函数的参数

上一小节的例子中类A 同时提供了不带参数和带参数的构造函数
构造函数可以是不带参数的这样对类的实例的初始化是固定的有时我们在
对类进行实例化时需要传递一定的数据来对其中的各种数据初始化使得初始化

不再是一成不变的这时我们可以使用带参数的构造函数来实现对类的不同实例
的不同初始化
在带有参数的构造函数中类在实例化时必须传递参数否则该构造函数不被执

让我们回顾一下10.2 节中关于车辆的类的代码示例我们在这里添加上构造函数
验证一下构造函数中参数的传递
程序清单10-6
using System;
class Vehicle//定义汽车类
{
public int wheels; //公有成员轮子个数
protected float weight; //保护成员重量
public Vehicle(){;}
public Vehicle(int w,float g){
wheels = w;
weight = g;
}
public void Show(){
Console.WriteLine(“the wheel of vehicle is:{0}”,wheels);
Console.WriteLine(“the weight of vehicle is:{0}”,weight);
}
};
class train //定义火车类
{
public int num; //公有成员车厢数目
private int passengers; //私有成员乘客数
private float weight; //私有成员重量
public Train(){;}
public Train(int n,int p,float w){
num = n;
passengers = p;
weight = w;
}
public void Show(){

Console.WriteLine(“the num of train is:{0}”,num);
Console.WriteLine(“the weight of train is:{0}”,weight);
Console.WriteLine(“the Passengers train car is:{0}”, Passengers);
}
}

class Car:Vehicle //定义轿车类
{
int passengers; //私有成员乘客数
public Car(int w,float g,int p) : base(w,g)
{
wheels = w;
weight = g;
passengers = p;
}
new public void Show(){
Console.WriteLine(“the wheel of car is:{0}”,wheels);
Console.WriteLine(“the weight of car is:{0}”,weight);
Console.WriteLine(“the Passengers of car is:{0}”, Passengers);
}
}
class Test
{
public static void Main(){
Vehicle v1 = new Vehicle(4,5);
Train t1 = new Train();
Train t2 = new Train(10,100,100);
Car c1 = new Car(4,2,4);
v1.show();
t1.show();
t2.show();
c1.show();
}
}
程序的运行结果为

the wheel of vehicle is:0
the weight of vehicle is: 0
the num of train is:0
the weight of train is:0
the Passengers of train is:0
the num of train is:10
the weight of train is:100
the Passengers of train is:100
the wheel of car is:4
the weight of car is:2
the Passengers of car is 4

原文地址:https://www.cnblogs.com/handsomer/p/4164322.html