c++之构造函数和析构函数

  1. 由于对象一定会在内存中占用一段空间,所以一定会有其生命周期。也就是说对象一定有申请内存空间和释放内存空间的步骤。

  2. 构造函数是当对象申请内存空间之后自动调用的函数;析构函数是当对象的空间即将被销毁前自动调用的函数。

  3. 构造函数的声明:①构造函数的声明需要在类中声明;②构造函数没有返回值;③构造函数的函数名必须和类名一致。

  4. 析构函数的声明:①析构函数的函数名以~+类名;②析构函数没有返回值;③析构函数没有参数列表。

#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

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值