析构函数的调用

mac2022-06-30  26

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

运行结果

ConstructingConstructingA=5B=15DestructingA=10B=15DestructingDestructingDestructingProgram ended with exit code: 0

拓展

如果修改static void f1(M &m);函数,直接传引用。 void M::f1(M &m){ cout<<"A="<<m.A<<endl; cout<<"B="<<B<<endl; } 运行结果ConstructingConstructingA=5B=15A=10B=15DestructingDestructingProgram ended with exit code: 0

Tips

警惕拷贝构造函数

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

最新回复(0)