类的构造函数、析构函数

#include <bits/stdc++.h>
using namespace std;
//类的定义
class student
{
public:
    student(string na="mark",string i="54163214"){ 
     //构造函数 没有类型,名字和类名相同,对象声明时自动调用 作用:初始化数据
        name=na;id=i;
        cout<<"it's created"<<endl;
    }
    ~student(){                        
    //析构函数  没有类型,类名前加一个~ ,对象生命期结束时自动调用 作用: 清理空间(动态数据必须在这清空)
        cout<<"it's done"<<endl;
    }
    void output_inf(){
        cout<<"his name is "<<name<<" and his id is "<<id<<endl;
    }
private :
    string name;
    string id;

};

int main()
{
    student a;
    a.output_inf();
    return 0;
}
//here is the output
//it's created
//his name is mark and his id is 54163214
//it's done
  

  

  关于类,还有一个重要的知识点:名字空间未说明

and more。。

落霞与孤鹜齐飞,秋水共长天一色
原文地址:https://www.cnblogs.com/star-and-me/p/6670518.html