// 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
- 警惕拷貝構造函數