C++入门经典-例7.3-析构函数的调用

1:析构函数的名称标识符就是在类名标识符前面加“~”。例如:

~CPerson();

2:实例代码:

(1)title.h

#include <string>//title是一个类,此为构造了一个类
#include <iostream>
using std::string;

class title{
public:
        title(string str);//这是一个构造函数
        title();//这是一个无参构造函数
        ~title();//这就是一个析构函数,执行的是收尾工作。
        string m_str;//成员变量
};
View Code

(2)title.cpp

#include "stdafx.h"
#include <iostream>
#include "title.h"
using std::cout;
using std::endl;
title::title(string str)
{
    m_str = str;
    cout<<str<<endl;
}
title::title()//此为空构造函数,当未定义构造函数时,编译器就会自动调用此函数
{
    m_str = "无名标题";
    cout<<"这只是一个无名标题标题..."<<endl;
}
title::~title()//这是一个析构函数,当类的对象被销毁时,编译器就会调用类的析构函数。
{
    cout<<"标题"<<m_str<<"要被销毁了"<<endl;
}
View Code

(3)main.cpp

// 7.3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "title.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
    string str("Hello World!!!!");
    title out(str);
    if (true)
    {
        title t;
    }
    cout << "if执行完成" << endl;
    return 0;
}
View Code

运行结果:

原文地址:https://www.cnblogs.com/lovemi93/p/7549971.html