国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

深入解析C++中的構造函數和析構函數

2020-01-26 15:54:48
字體:
來源:轉載
供稿:網友

構造函數:
在類實例化對象時自動執行,對類中的數據進行初始化。構造函數可以從載,可以有多個,但是只能有一個缺省構造函數。

析構函數:
在撤銷對象占用的內存之前,進行一些操作的函數。析構函數不能被重載,只能有一個。

調用構造函數和析構函數的順序:
先構造的后析構,后構造的先折構。它相當于一個棧,先進后出。

復制代碼 代碼如下:

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



先構造的千手,結果后析構的千手;后構造的綱手,結果先折構的綱手。

特點:
在全局范圍定義的對象和在函數中定義的靜態(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","靜態局部變量");//定義靜態局部變量
 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;
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南澳县| 浑源县| 桃园县| 崇阳县| 台安县| 陇南市| 大埔区| 泉州市| 遵化市| 高淳县| 霞浦县| 阿巴嘎旗| 沾化县| 项城市| 宁乡县| 永昌县| 阿拉善右旗| 绥德县| 浦江县| 车致| 苍溪县| 正蓝旗| 远安县| 彩票| 乌恰县| 巴东县| 浏阳市| 广昌县| 天门市| 珠海市| 绥化市| 通辽市| 绍兴县| 平遥县| 张家港市| 大同县| 桓台县| 太湖县| 禹州市| 昔阳县| 周至县|