析构函数的调用

//  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

  • 警惕拷贝构造函数

猜你喜欢

转载自www.cnblogs.com/overlows/p/10673117.html