-
由于对象一定会在内存中占用一段空间,所以一定会有其生命周期。也就是说对象一定有申请内存空间和释放内存空间的步骤。
-
构造函数是当对象申请内存空间之后自动调用的函数;析构函数是当对象的空间即将被销毁前自动调用的函数。
-
构造函数的声明:①构造函数的声明需要在类中声明;②构造函数没有返回值;③构造函数的函数名必须和类名一致。
-
析构函数的声明:①析构函数的函数名以~+类名;②析构函数没有返回值;③析构函数没有参数列表。
#include "stdafx.h"
#include <string.h>
#include <iostream>
using namespace std;
class Student {
private:
char name[20];
double score;
int id;
public:
Student();
Student(const char* name,double score,int id);
~Student();
void printFun();
void showStudentInfo();
};
Student::Student()
{
cout << "Student::Student()" << endl;
}
Student::Student(const char* name, double score, int id)
:score(score),id(id)
{
cout << "Student::Student(const char* name, double score, int id)" << endl;
strncpy(this->name, name,20);
}
Student::~Student()
{
cout << "Student::~Student()" << endl;
}
void Student::printFun()
{
cout << "Student::printFun()" << endl;
}
void Student::showStudentInfo()
{
cout << "name:" << name << endl;
cout << "score:" << score << endl;
cout << "id:" << id << endl;
}
int main()
{
Student stu;//调用无参的构造函数
stu.printFun();
cout << "=======" << endl;
Student stu2("Tom", 88, 001);//调用有参的构造函数
stu2.showStudentInfo();
return 0;
}
执行输出:
由上图可以知道,调用了两次构造函数和两次析构函数。
ps:如果在使用vs的过程中出现'strncpy': This function or variable may be unsafe. Consider using strncpy_s instead,可以看下下面的链接:
https://blog.csdn.net/weixin_38363517/article/details/80068542