類的建構函式、解構函式、拷貝建構函式、賦值函式
類的四種基本預設函式:建構函式、解構函式、拷貝建構函式、賦值函式。
建構函式:建立類時,系統自動呼叫建構函式,用以初始化,分配空間,沒有自定義的建構函式時,系統預設一個無引數的建構函式。
class book
{
private:
int isBook;
string BookName;
public:
book() //建構函式
{
cout<<"Construct!"<<endl;
}
book(int
{
cout<<"Construct with "<<ib<<" "<<bn<<endl;
};
}
解構函式:當物件超出其定義範圍時(即釋放該物件時),編譯器自動呼叫解構函式。 如果一個物件被定義在一個函式體內,則當這個函式結束時,該物件的解構函式被自動呼叫。 若一個物件是使用new運算子動態建立的,在使用delete運算子釋放它時,delete將會自動呼叫解構函式。用new建立的物件,必須用delete銷燬。
~book() //解構函式
{
cout<<"Destruct!"<<endl;
}
拷貝建構函式:
book a(1,"History");
book b=a;
當此類呼叫時系統會呼叫拷貝建構函式。
如果不自定義拷貝建構函式,系統會自動將變數拷貝給新的類。
book(const book &a) //拷貝函式
{
cout<<"Copy!"<<endl;
this->isBook=a.isBook;
this->BookName=a.BookName;
}
賦值函式:原類已被構建,用另一個類給其賦值時系統呼叫。與拷貝函式的區別在於,呼叫賦值函式說明原類已有值:
book a(1,"History");
book b;
b=a;
book& operator =(const book& a) //賦值函式
{
cout<<"Assign with "<<a.isBook<<" "<<a.BookName<<endl;
this->BookName=a.BookName;
this->isBook=a.isBook;
return *this;
}
全部程式碼測試:
//
// main.cpp
// ClassStudy
//
// Created by 王一帆 on 2018/9/30.
// Copyright © 2018 王一帆. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
class book
{
private:
int isBook;
string BookName;
public:
book() //建構函式
{
cout<<"Construct!"<<endl;
}
book(int ib,string bn):isBook(ib),BookName(bn) //建構函式
{
cout<<"Construct with "<<ib<<" "<<bn<<endl;
};
~book() //解構函式
{
cout<<"Destruct!"<<endl;
}
book(const book &a) //拷貝函式
{
cout<<"Copy!"<<endl;
this->isBook=a.isBook;
this->BookName=a.BookName;
}
book& operator =(const book& a) //賦值函式
{
cout<<"Assign with "<<a.isBook<<" "<<a.BookName<<endl;
this->BookName=a.BookName;
this->isBook=a.isBook;
return *this;
}
int getIsBook()
{
return isBook;
}
string getBookName()
{
return BookName;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
book a(1,"History");
book b=book(a);
book c;
c=a;
cout<<b.getIsBook()<<" "<<b.getBookName()<<endl;
return 0;
}
輸出結果為:
Construct with 1 History a的建構函式的呼叫
Copy! a的拷貝建構函式(將a拷貝給b)
Construct! c的建構函式
Assign with 1 History c的賦值函式
1 History 輸出b的資訊
Destruct! 函式終止時,按c,b,a的順序依次呼叫其解構函式
Destruct!
Destruct!
Program ended with exit code: 0