深入解析C++中的構造函數和析構函數
構造函數:
在類實例化對象時自動執(zhí)行,對類中的數據進行初始化。構造函數可以從載,可以有多個,但是只能有一個缺省構造函數。
析構函數:
在撤銷對象占用的內存之前,進行一些操作的函數。析構函數不能被重載,只能有一個。
調用構造函數和析構函數的順序:
先構造的后析構,后構造的先折構。它相當于一個棧,先進后出。
#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;
}
先構造的千手,結果后析構的千手;后構造的綱手,結果先折構的綱手。
特點:
在全局范圍定義的對象和在函數中定義的靜態(tài)(static)局部對象,只在main函數結束或者調用exit函數結束程序時,才調用析構函數。
如果是在函數中定義的對象,在建立對象時調用其構造函數,在函數調用結束、對象釋放時先調用析構函數。
#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<<"============調用fun函數============"<<endl<<endl;
Student s2("002","自動局部變量");//定義自動局部對象
s2.show();
static Student s3("003","靜態(tài)局部變量");//定義靜態(tài)局部變量
s3.show();
cout<<"===========fun函數調用結束=============="<<endl<<endl;
}
int main(){
Student s1("001","全局變量");
s1.show();
fun();
cout<<"\nthis is some content before the end\n";//這是一段位于main函數結束之前,函數調用之后的內容
cout<<endl;
return 0;
}
欄 目:C語言
下一篇:一道超經典的C++結構體的題目
本文標題:深入解析C++中的構造函數和析構函數
本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/4201.html
您可能感興趣的文章
- 04-02c語言沒有round函數 round c語言
- 01-10深入理解約瑟夫環(huán)的數學優(yōu)化方法
- 01-10深入二叉樹兩個結點的最低共同父結點的詳解
- 01-10數據結構課程設計- 解析最少換車次數的問題詳解
- 01-10深入理解C++中常見的關鍵字含義
- 01-10使用C++實現全排列算法的方法詳解
- 01-10深入Main函數中的參數argc,argv的使用詳解
- 01-10深入第K大數問題以及算法概要的詳解
- 01-10深入解析最長公共子串
- 01-10c++中inline的用法分析


閱讀排行
本欄相關
- 04-02c語言函數調用后清空內存 c語言調用
- 04-02func函數+在C語言 func函數在c語言中
- 04-02c語言的正則匹配函數 c語言正則表達
- 04-02c語言用函數寫分段 用c語言表示分段
- 04-02c語言中對數函數的表達式 c語言中對
- 04-02c語言編寫函數冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數 round c語言
- 04-02c語言分段函數怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數 c語言中怎
- 04-02c語言調用函數求fibo C語言調用函數求
隨機閱讀
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 04-02jquery與jsp,用jquery
- 01-10delphi制作wav文件的方法
- 01-10SublimeText編譯C開發(fā)環(huán)境設置
- 01-10C#中split用法實例總結
- 08-05dedecms(織夢)副欄目數量限制代碼修改
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-11ajax實現頁面的局部加載
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 08-05織夢dedecms什么時候用欄目交叉功能?