欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

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

來源:本站原創(chuàng)|時間:2020-01-10|欄目: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++的sstream標準庫詳細介紹

欄    目:C語言

下一篇:一道超經典的C++結構體的題目

本文標題:深入解析C++中的構造函數和析構函數

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/4201.html

網頁制作CMS教程網絡編程軟件編程腳本語言數據庫服務器

如果侵犯了您的權利,請與我們聯系,我們將在24小時內進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

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

Copyright © 2002-2020 腳本教程網 版權所有