1.构造函数
C++中有这么一种特殊的函数,它在类里,与类名同名,且没有返回值的一个函数,只要我们定义一个类的对象,系统就会自动调用它,进行专门的初始化对象用,而大多数情况下,因为我们没有定义构造函数,系统会默认生成一个默认形式、隐藏着的构造函数,这个构造函数的函数体是空着的,因此不具有任何功能。
那么下来,我们将教大家如何定义自己的构造函数,需要用户自行定义了至少一个构造函数,系统就不在自动生成,而是根据用户定义的构造函数选择最匹配的一个进行调用。
例如还是Student类的例子,我们添加一个带有默认参数的构造函数,代码如下:
#include<iostream>
#include<Cstring>
using namespace std;
class Student
{
private:
int num;//学号
char name[100];//名字
int score;//成绩
public:
Student(int n,char *str,int s);
int print();
int Set(int n,char *str,int s);
};
Student::Student(int n,char *str,int s)
{
num = n;
strcpy(name,str);
score = s;
cout<<"Constructor"<<endl;
}
int Student::print()
{
cout<<num<<" "<<name<<" "<<score;
return 0;
}
int Student::Set(int n,char *str,int s)
{
num = n;
strcpy(name,str);
score = s;
}
int main()
{
Student A(100,"dotcpp",11);//定义的时候同时调用
A.print();
return 0;
}
2.析构函数
与构造函数不同的是,虽然他俩都为公开类型。构造可以重载,有多个兄弟,而析构却不能重载,但它可以是虚函数,一个类只能有一个析构函数。
下面,我们以Student类为例,继续添加析构函数,同时在构造函数和析构函数中都添加了输出当前类的信息,用来辨别哪一个类的创建和销毁:
#include<iostream>
#include<Cstring>
using namespace std;
class Student
{
private:
int num;//学号
char name[100];//名字
int score;//成绩
public:
Student(int n,char *str,int s);
~Student();
int print();
int Set(int n,char *str,int s);
};
Student::Student(int n,char *str,int s)
{
num = n;
strcpy(name,str);
score = s;
cout<<num<<" "<<name<<" "<<score<<" ";
cout<<"Constructor"<<endl;
}
Student::~Student()
{
cout<<num<<" "<<name<<" "<<score<<" ";
cout<<"destructor"<<endl;
}
int Student::print()
{
cout<<num<<" "<<name<<" "<<score<<endl;
return 0;
}
int Student::Set(int n,char *str,int s)
{
num = n;
strcpy(name,str);
score = s;
}
int main()
{
Student A(100,"dot",11);
Student B(101,"cpp",12);
return 0;
}
可以看到对象A和B的构造函数的调用顺序以及构造函数的调用顺序,完全相反!原因在于A和B对象同属局部对象,也在栈区存储,也遵循“先进后出”的顺序!