当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 析构函数的调用

析构函数的调用

2019年04月09日  | 移动技术网IT编程  | 我要评论

牛头梗价格,中国谷城网,耳鼻喉专家徐明栓

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

  • 警惕拷贝构造函数

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网