书上说:“构造函数初始化语句可以让构造过程使用当前类中其他的构造函数” public myclass(int x):this (x,"bilibili") //////////////////////////////////////////////////以下是我的实验:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class father { public string name="delphi"; public father(int age) { Console.WriteLine("the father 's age is:{0}",age); } public father() { } public void print() { Console.WriteLine("the father class delphi."); } virtual public void goodfather() { Console.WriteLine("this is virtual father!!!!!!!!"); } } class son:father { new public string name = "web"; public son(int age):base(age) { }//important public son(int age,char sex,string hobby) { Console.WriteLine("age sex hobby ----3:{0},:{1},:{2}.",age,sex,hobby); } public son(int age,char sex):this(age,sex,"basketball") { Console.WriteLine("the son's age is{0},and sex is {1}:", age, sex); } public son() { } public void print() { Console.WriteLine("{0}",base.name); } public override void goodfather() { Console.WriteLine("this is child class 's goodfather."); } } class Program { static void Main(string[] args) { son s = new son(18); father f = new father(20); son s2 = new son(18, '1', "pool"); son s3 = new son(12); son s4 = new son(12, 'd'); //father f2 = (father)s; /*Console.WriteLine("{0}:", s.name); s.print(); f2.print(); Console.WriteLine("{0}:", f2.name); f.goodfather(); f2.goodfather();*/ } } }
但是结果是这样的:
那摩问题来了,按照书上说是对应我这里是3变量那个初试两变量那个,可是他只是又调用了一次三变量构造函数,完全没有像书上说的对两变量构造函数做初始化,,,还是我用错了?求指教。。。(见结果倒数第1,2行)
(《0^0》)
class Program { static void Main(string[] args) { son s1 = new son(18); son s2 = new son(12, 'd'); son s3 = new son(18, '1', "pool"); Console.ReadKey(); } } class son { public string name = "web"; public son() : this(0,'m',"") { } public son(int age) : this(age,'m', "") { } public son(int age, char sex) : this(age, sex, "basketball") { } public son(int age, char sex, string hobby) { Console.WriteLine("age sex hobby ----3:{0},:{1},:{2}.", age, sex, hobby); } }
用:this()来构造你把它想成是踢皮球,把皮球踢给最多参数那个,在最多参数那个构造里面实现就成了
谢谢,意思其实是调用多参数构造。?。。。!谢谢你
你有疑问的是son s4 = new son(12, 'd');这行吧,执行到这一句时,先执行了this(age,sex,"basketball"),输出age sex hobby---,然后执行自身,输出the son's age is...
那,我要是想实现书上说的那样,用多参数构造函数初始化少参数构造函数,该怎么写呢
@邗影: 初始化少参数构造函数指的是什么
@jello chen: 我是说例如:用两参数构造函数初始化一个参数的构造函数,用this想实现书中说的那样,怎么写呢
谢谢,我大概能理解你的意思了。谢谢喽。