类的构造函数与析构函数

8、小作业:
有这么个函数:

void test()
{
    CStudent zhang_san("zhangsan", 'f', 1001, 21);
    CStudent li_si("lisi", 'm', 1002, 22);
    CStudent wang_wu("wangwu", 'm', 1003, 23);
}

在 test 函数中我依次定义了三个局部变量的对象:zhang_san、li_si、wang_wu,那么当离开 test 函数之后,这三个对象的析构顺序又是怎么样的呢?大家先想想,之后在VS编译器中试试,验证下你的猜想到底对不对,为什么会这样呢?

先一个个构造,在一个个析构。

#pragma once
#include <iostream>
using namespace std;
#pragma warning(disable:4996)
class NewStudent
{
    char* p_name;
    char sex;
    unsigned int num;
    unsigned int age;
public:
    NewStudent(char* t_name,char t_sex, unsigned int t_num,unsigned int t_age);
    ~NewStudent();
};
#include "NewStudent.h"
NewStudent::NewStudent(char* t_name, char t_sex, unsigned int t_num, unsigned int t_age)
{
    int t_len = strlen(t_name);
    p_name = new char[t_len+1];
    memset(p_name, 0, t_len + 1);
    strcpy(p_name,t_name);
    cout << "构造函数触发" << endl;
}
NewStudent::~NewStudent()
{
    delete[] p_name;
    static int  t = 1;
    cout << "析构函数触发" << t << endl;
    t++;
}
#include <iostream>
#include "NewStudent.h"
using namespace std;
void test()
{
    NewStudent aatuds("aatuds", 'm', 1, 1);
    cout << "第1个函数下面" << endl;
    NewStudent yyyw("yyyw", 'm', 1, 1);
    cout << "第2个函数下面" << endl;
    NewStudent zsfs("zsfs", 'm', 1, 1);
    cout << "第3个函数下面" << endl;
}
int main()
{
    test();

    return 0;
}

 

posted on 2021-01-07 19:28  SakuraQAQ  阅读(127)  评论(0)    收藏  举报

导航