A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 许全通 黑马帝   /  2012-2-21 11:04  /  1946 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 许全通 于 2012-2-25 21:44 编辑

有一段代码:
class Student
    {
        public Student()  { }
        public Student(string name, Genders gender, int age, string hobby) : this(name, gender, age, hobby, 100) { }
        public Student(string name, Genders gender, int age, string hobby, int popularity)
        {
            this.Name = name;
            this.Gender = gender;
            this.Age = age;
            this.Hobby = hobby;
            this.Popularity = popularity;
        }
   }
其中第二个构造函数后的冒号“:”还有后面的this是什么意思啊?

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

5 个回复

倒序浏览
如果我没有看错,应该就是继承了,下面的函数!如有不对,请指教啊!

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

回复 使用道具 举报
构造函数它主要用于为对象分配存储空间,对数据成员进行初始化.
对于构造函数可以看下面:
构造函数的名字必须与类同名;

构造函数没有返回类型,它可以带参数,也可以不带参数;

构造函数可重载,默认没有参数,有参数的提供构造函数,必须自己来写没参数的构造函数

引用父类构造时用():base()方法,引用自身重载的构造使用():this(para).

你这种情况应该属于最后一种,引用自身引用自身重载的构造使用

因为这段代码的参数“: this(name, gender, age, hobby, 100) { }”

与 public Student(string name, Genders gender, int age, string hobby, int popularity)

参数类型相同,所实现的构造也差不多,只是需要输入4个参数即可,最后一个popularity参数默认为100而已

继承有那么一点点,因为派生类初始化的时候,先初始化父类的构造函数。

对于,引用父类构造时用():base()方法

class ParentClass
{ private int x;
 public ParentClass( ) { x = 0; }
 public ParentClass( int i ) { x = i; }
};
class childClass : ParentClass
{ private int y;
 public childClass ( ) { y = 0; }
 public childClass ( int i ) { y = i; }
 public childClass ( int i, int j ):A(i) { y = j; }
};
childClass  c1 = new childClass (); //执行基类ParentClass的构造函数ParentClass(),再执行派生类的构造函数childClass ()
childClass  c2 = new childClass (1); //执行基类ParentClass的构造函数ParentClass(),再执行派生类的构造函数childClass (int)
childClass  c3 = new childClass (0,1); //执行执行基类ParentClass的构造函数A(int) ,再执行派生类的


对不对敲敲代码吧!若不还请多指教

评分

参与人数 1技术分 +2 收起 理由
郑文 + 2

查看全部评分

回复 使用道具 举报
this代表当前对象,this(parameters)代表引用自身的构造函数
你也可以在类的成员中使用this
如:你的类中的 this.Name = name;     this.Name为当前对象的成员(属性或全局变量)

评分

参与人数 1技术分 +1 收起 理由
郑文 + 1

查看全部评分

回复 使用道具 举报
this就是指当前的对象,用一个最简单的例子来说明吧
在WinFrom程序中你写一个this.Text=“第一个窗口”,程序在运行时就会在窗体
的标题栏显示第一个窗口的字样,其中这个this 就是指代当前的对象Form1

评分

参与人数 1技术分 +1 收起 理由
郑文 + 1

查看全部评分

回复 使用道具 举报
本帖最后由 安超 于 2012-2-25 14:33 编辑

         一、public Student()  { }
         二、public Student(string name, Genders gender, int age, string hobby) : this(name, gender, age, hobby, 100) { }
         三、public Student(string name, Genders gender, int age, string hobby, int popularity)
         {
             this.Name = name;
             this.Gender = gender;
             this.Age = age;
             this.Hobby = hobby;
             this.Popularity = popularity;
         }

你问的问题的标准答案:“二”这个构造方法继承自“三”!!!

评分

参与人数 1技术分 +1 收起 理由
郑文 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马