7.构造函数和析构函数
在C++中,构造函数就是初始化类的实例即对象(开辟内存空间),构造函数就是销毁对象(回收空间)。
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
Student1 s1 = new Student1(12);
Student2 s2 = new Student2(14,"guojun");
Console.WriteLine( "姓名:{0},年龄:{1}",s2.name,s2.age );
Console.WriteLine("姓名:{0}", s1.age);
Console.WriteLine("姓名:{0},年龄:{1}", s.name,s.age);
}
}
public class Student
{
public int age;
public string name;
public Student() { }
public Student(int a)
{
this.age = a;
}
public Student(int a, string n)
{
this.age = a;
this.name = n;
}
~Student()
{
Console.WriteLine( "Student的析构函数被调用" );
}
}
public class Student1 : Student
{
public Student1() { }
public Student1(int a)
{
this.age = a;
}
public Student1(int a, string n)
{
this.age = a;
this.name = n;
}
~Student1()
{
Console.WriteLine("Student1的析构函数被调用");
}
}
public class Student2 : Student
{
public Student2() { }
public Student2(int a)
{
this.age = a;
}
public Student2(int a, string n)
{
this.age = a;
this.name = n;
}
~Student2()
{
Console.WriteLine("Student2的析构函数被调用");
}
}
}
注意几点:1.构造函数与析构函数不能被继承,构造函数能被重载。
2.析构函数调用顺序与构造函数相反。