構造函數: 在類實例化對象時自動執行,對類中的數據進行初始化。構造函數可以從載,可以有多個,但是只能有一個缺省構造函數。 析構函數: 在撤銷對象占用的內存之前,進行一些操作的函數。析構函數不能被重載,只能有一個。 調用構造函數和析構函數的順序: 先構造的後析構,後構造的先折構。它相當於一個棧,先進後出。
#include<iostream>
#include<string>
using namespace std;
class Student{
public:
Student(string,string,string);
~Student();
void show();
private:
string num;
string name;
string sex;
};
Student::Student(string nu,string na,string s){
num=nu;
name=na;
sex=s;
cout<<name<<" is builded!"<<endl;
}
void Student::show(){
cout<<num<<"\t"<<name<<"\t"<<sex<<endl;
}
Student::~Student(){
cout<<name<<" is destoried!"<<endl;
}
int main(){
Student s1("001","千手","男");
s1.show();
Student s2("007","綱手","女");
s2.show();
cout<<"nihao"<<endl;
cout<<endl;
cout<<"NIHAO"<<endl;
return 0;
}