c/c++语言开发共享析构函数的调用

“` // main.cpp // 构造函数析构函数练习 // Created by mac on 2019/4/8. // Copyright © 2019年 mac. All rights reserved. // 1.编译器总是在调用派生类构造函数之前调用基类的构造函数 // 2.派生类的析 …

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

  • 警惕拷贝构造函数

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/604357.html

(0)
上一篇 2021年5月12日
下一篇 2021年5月12日

精彩推荐