析构函数的调用

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

  • 警惕拷贝构造函数

转载于:https://www.cnblogs.com/overlows/p/10673117.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值