析構函數的調用


//  main.cpp
//  構造函數析構函數練習
//  Created by mac on 2019/4/8.
//  Copyright © 2019年 mac. All rights reserved.
//  1.編譯器總是在調用派生類構造函數之前調用基類的構造函數
//  2.派生類的析構函數會在基類的析構函數之前調用。
//  3.析構函數屬於成員函數,當對象被銷毀時,該函數被自動調用。
//
//

#include <iostream>
using namespace std;
class M{
private:
    int A;
    static int B;
    
public:
    M(int a)
    {
        A = a;
        B+=a;
        cout<<"Constructing"<<endl;
    }
    
    static void f1(M m);
    ~M(){
        cout<<"Destructing"<<endl;
    }
};

void M::f1(M m){
    cout<<"A="<<m.A<<endl;
    cout<<"B="<<B<<endl;
}

int M::B=0;

int main(int argc, const char * argv[]) {
    M P(5),Q(10);
    M::f1(P);
    M::f1(Q);
    return 0;
}


運行結果

Constructing
Constructing
A=5
B=15
Destructing
A=10
B=15
Destructing
Destructing
Destructing
Program ended with exit code: 0

拓展

  • 如果修改static void f1(M &m);函數,直接傳引用。
void M::f1(M &m){
    cout<<"A="<<m.A<<endl;
    cout<<"B="<<B<<endl;
}
  • 運行結果
    Constructing
    Constructing
    A=5
    B=15
    A=10
    B=15
    Destructing
    Destructing
    Program ended with exit code: 0

Tips

  • 警惕拷貝構造函數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM