什么是构造方法(我看不懂了)?
构造方法:
实例化对象时确定要调用一个方法.这个方法称为构造方法.
我们必须要么自己在类定义中定义一个,要么让CLR替我们提供
一个.
构造方法的工作是创建某个类所指定的对象,并将它置于有
效状态.
在构造方法运行前,对象只是无法区分的内存,在构造方法完成后,内存就存放了某个类型的一个有效实例.
定义结构方法时需要声明一个与类同名的方法.
此例的Time类并末定义构造方法.
using System;
public class Time
{
//公共方法
public void DisplayCurrentTime()
{
Console.WriteLine(
"stub for DisplayCurrentTime");
}
//私有变量
int Year;
int Month;
int Date;
int Hour;
int Minute;
int Second;
}
public class Tester
{
static void Main()
{
Time t=new Time();
t.DisplayCurrentTime();
}
}
例 ,声明构造方法
public class Time
{
//公共访问方法
public void DisplayCurrentTime()
{
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
Month,Date,Year,Hour,Minute,Second);
}
//构造方法
public Time(System.DataTime dt)
{
Year =dt.Year;
Month =dt.Month;
Date=dt.Day;
Hour=dt.Hour
Minute=dt.Minute;
Second=dt.Second;
}
//私有成员变量
int Year;
int Month;
int Date;
int Hour;
int Minute;
int Second;
}
public class Tester
{
static void Main()
{
System.DateTime currentTime =System.DateTime.Now;
Time t= new Time(currentTime);
t.DisplayCurrentTime();
}
}
/////////////////////////////////////////////////////
看了以上内容,我还是不明白什么是构造方法?它的作用是什么?
因为没学过C++,JAVA,对类的知识不是很明白.还请各位前辈给我讲解一下?