雷火电竞-中国电竞赛事及体育赛事平台

歡迎來(lái)到入門(mén)教程網(wǎng)!

C語(yǔ)言

當(dāng)前位置:主頁(yè) > 軟件編程 > C語(yǔ)言 >

深入解析C++中的構(gòu)造函數(shù)和析構(gòu)函數(shù)

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語(yǔ)言|點(diǎn)擊:

構(gòu)造函數(shù):
在類實(shí)例化對(duì)象時(shí)自動(dòng)執(zhí)行,對(duì)類中的數(shù)據(jù)進(jìn)行初始化。構(gòu)造函數(shù)可以從載,可以有多個(gè),但是只能有一個(gè)缺省構(gòu)造函數(shù)。

析構(gòu)函數(shù):
在撤銷對(duì)象占用的內(nèi)存之前,進(jìn)行一些操作的函數(shù)。析構(gòu)函數(shù)不能被重載,只能有一個(gè)。

調(diào)用構(gòu)造函數(shù)和析構(gòu)函數(shù)的順序:
先構(gòu)造的后析構(gòu),后構(gòu)造的先折構(gòu)。它相當(dāng)于一個(gè)棧,先進(jìn)后出。

復(fù)制代碼 代碼如下:

#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;
}



先構(gòu)造的千手,結(jié)果后析構(gòu)的千手;后構(gòu)造的綱手,結(jié)果先折構(gòu)的綱手。

特點(diǎn):
在全局范圍定義的對(duì)象和在函數(shù)中定義的靜態(tài)(static)局部對(duì)象,只在main函數(shù)結(jié)束或者調(diào)用exit函數(shù)結(jié)束程序時(shí),才調(diào)用析構(gòu)函數(shù)。

如果是在函數(shù)中定義的對(duì)象,在建立對(duì)象時(shí)調(diào)用其構(gòu)造函數(shù),在函數(shù)調(diào)用結(jié)束、對(duì)象釋放時(shí)先調(diào)用析構(gòu)函數(shù)。

復(fù)制代碼 代碼如下:

#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","自動(dòng)局部變量");//定義自動(dòng)局部對(duì)象
 s2.show();
 static Student s3("003","靜態(tài)局部變量");//定義靜態(tài)局部變量
 s3.show();
 cout<<"===========fun函數(shù)調(diào)用結(jié)束=============="<<endl<<endl;
}
int main(){
 Student s1("001","全局變量");
 s1.show();
 fun();
 cout<<"\nthis is some content before the end\n";//這是一段位于main函數(shù)結(jié)束之前,函數(shù)調(diào)用之后的內(nèi)容
 cout<<endl;
 return 0;
}

上一篇:C++的sstream標(biāo)準(zhǔn)庫(kù)詳細(xì)介紹

欄    目:C語(yǔ)言

下一篇:一道超經(jīng)典的C++結(jié)構(gòu)體的題目

本文標(biāo)題:深入解析C++中的構(gòu)造函數(shù)和析構(gòu)函數(shù)

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/4201.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有