深入解析C++中的構造函數(shù)和析構函數(shù)
構造函數(shù):
在類實例化對象時自動執(zhí)行,對類中的數(shù)據(jù)進行初始化。構造函數(shù)可以從載,可以有多個,但是只能有一個缺省構造函數(shù)。
析構函數(shù):
在撤銷對象占用的內(nèi)存之前,進行一些操作的函數(shù)。析構函數(shù)不能被重載,只能有一個。
調(diào)用構造函數(shù)和析構函數(shù)的順序:
先構造的后析構,后構造的先折構。它相當于一個棧,先進后出。
#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;
}
先構造的千手,結果后析構的千手;后構造的綱手,結果先折構的綱手。
特點:
在全局范圍定義的對象和在函數(shù)中定義的靜態(tài)(static)局部對象,只在main函數(shù)結束或者調(diào)用exit函數(shù)結束程序時,才調(diào)用析構函數(shù)。
如果是在函數(shù)中定義的對象,在建立對象時調(diào)用其構造函數(shù),在函數(shù)調(diào)用結束、對象釋放時先調(diào)用析構函數(shù)。
#include<iostream>
#include<string>
using namespace std;
class Student{
public:
Student(string,string);
~Student();
void show();
string num;
string name;
};
Student::Student(string nu,string na){
num=nu;
name=na;
cout<<name<<" is builded!"<<endl<<endl;
}
void Student::show(){
cout<<num<<"\t"<<name<<endl<<endl;
}
Student::~Student(){
cout<<name<<" is destoried!"<<endl<<endl;
}
void fun(){
cout<<"============調(diào)用fun函數(shù)============"<<endl<<endl;
Student s2("002","自動局部變量");//定義自動局部對象
s2.show();
static Student s3("003","靜態(tài)局部變量");//定義靜態(tài)局部變量
s3.show();
cout<<"===========fun函數(shù)調(diào)用結束=============="<<endl<<endl;
}
int main(){
Student s1("001","全局變量");
s1.show();
fun();
cout<<"\nthis is some content before the end\n";//這是一段位于main函數(shù)結束之前,函數(shù)調(diào)用之后的內(nèi)容
cout<<endl;
return 0;
}
相關文章
Qt?Creator配置opencv環(huán)境的全過程記錄
最近在PC端QT下配置opencv,想著以后應該會用到,索性記錄下,這篇文章主要給大家介紹了關于Qt?Creator配置opencv環(huán)境的相關資料,需要的朋友可以參考下2022-05-05C++中for循環(huán)與while循環(huán)的區(qū)別總結
這篇文章主要給大家介紹了關于C++中for循環(huán)與while循環(huán)的區(qū)別的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10