C#例题——析构函数和构造函数

来源:互联网 发布:仿淘宝购物车的htmlcss 编辑:程序博客网 时间:2024/06/15 13:25

问题描述:

构造Person类,在此基础上体验构造函数和虚构函数,构造函数有参和无参的区别

程序代码:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 构造析构函数{    class Program    {        static void Main(string[] args)        {            Person p1 = new Person();            Console.Write("调用无参函数:");            p1.ShowPersonMsg();            Person p2 = new Person("杰克", 28);            Console.Write("调用有参函数:");            p2.ShowPersonMsg();            Console.ReadKey();            }    }    class Person    {        public string name;        int age;        protected string sex;        public Person()        {}        public Person(string xm, int nl)        {            name = xm;            age = nl;        }        public void ShowPersonMsg()        {            Console.WriteLine("姓名:{0},年龄:{1},", name, age);        }    }}

运行结果:


心得体会:

注意区分无参构造函数与默认构造函数的区别,在没有无参构造函数时,会自动生成一个默认构造函数,但是在已经定义的无参构造函数,调用就会调用已经定义的

0 0
原创粉丝点击