C_构造函数的重载我是C语言爱好者.doc_第1页
C_构造函数的重载我是C语言爱好者.doc_第2页
C_构造函数的重载我是C语言爱好者.doc_第3页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

C#构造函数的重载C#中的构造函数也可以应用方法重载。C#中有默认构造函数,也可以定义带参数的构造函数。构造函数必须与类同名,并且不能有返回值。所以C#构造函数重载相当于不同数量的参数方法重载。所谓重载构造函数是指允许在类中有多个构造函数。当然这些构造函数肯定是有区别的。各个构造函数必须拥有不同的参数个数或者类型using System;class Animalpublic string _name;public string _color;public int _speed;public Animal() this._speed = 30;/this 表示public Animal(string name, string color) this._name = name; this._color = color;public Animal(string name, string color, int speed) this._name = name; this._color = color; this._speed = speed;class Programstatic void Main(stringargs) /方法一 Animal animal1 = new Animal(); animal1._name = 兔子; animal1._color = 灰色; /animal1._speed = 40; Console.WriteLine( 调用默认构造函数输出动物为0,颜色为1,奔跑速度为2km/h, animal1._name, animal1._color, animal1._speed); /方法二 Animal animal2 = new Animal(狗, 黄色); Console.WriteLine(调用两个参数构造函数输出动物为0,颜色为1, animal2._name, animal2._color); /方法三 Animal animal3 = new Animal(花猫, 白色, 20); Console.WriteLine( 调用三个参数构造函数输出动物为0,颜色为1,奔跑速度为2, animal3._name, animal3._color, animal3._speed); Console.WriteLine(一只 + animal3._color + 的 + animal3._name + 正在以 + animal3._speed + km/h的速度在奔跑n); Console.ReadLine();我们再看一个例子:using System;class Programprivate string _name;private int _age;private string _qualification;public Program() _age = 18;public Program(string name, int age, string qualification) this._name = name; this._age = age; this._qualification = qualification;static void Main() Program p = new Program(); Console.WriteLine(默认构造函数输出年龄为 + p._age); Program p1 = new Program(李公, 19, 大学); Console.Wr

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论