C++类构造析构调用顺序训练(复习专用)
生活随笔
收集整理的這篇文章主要介紹了
C++类构造析构调用顺序训练(复习专用)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//對象做函數參數
//1 研究拷貝構造
//2 研究構造函數,析構函數的調用順序//總結 構造和析構的調用順序#include "iostream"
using namespace std;class ABCD
{ //this()
public:ABCD(int a, int b, int c){this->a = a;this->b = b;this->c = c;printf("ABCD() construct, a:%d,b:%d,c:%d \n", this->a, this->b, this->c);}~ABCD(){printf("~ABCD() construct,a:%d,b:%d,c:%d \n", this->a, this->b, this->c);}int getA(){return this->a;}
protected:
private:int a;int b;int c;
};class MyE
{
public:MyE() :abcd1(1, 2, 3), abcd2(4, 5, 6), m(100){cout << "MyD()" << endl;}~MyE(){cout << "~MyD()" << endl;}MyE(const MyE & obj) :abcd1(7, 8, 9), abcd2(10, 11, 12), m(100){printf("MyD(const MyD & obj)\n");}protected://private:
public:ABCD abcd1; //c++編譯器不知道如何構造abc1ABCD abcd2;const int m;};int doThing(MyE mye1)
{printf("doThing() mye1.abc1.a:%d \n", mye1.abcd1.getA());return 0;
}int run2()
{MyE myE;doThing(myE);return 0;
}//
int run3()
{printf("run3 start..\n");ABCD abcd = ABCD(100, 200, 300); //用臨時對象來初始化一個對象,就會把臨時對象變化成要初始化的對象,而不會調用copy構造函數,臨時對象也不用將自己賦值給對方,然后自己銷毀這么麻煩.//ABCD(400, 500, 600); //臨時對象的生命周期printf("run3 end\n");return 0;
}int main()
{run2();//run3();system("pause");return 0;
}
輸出\
轉載于:https://www.cnblogs.com/c-slmax/p/5183134.html
總結
以上是生活随笔為你收集整理的C++类构造析构调用顺序训练(复习专用)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python实现PLA(感知机)
- 下一篇: C++命名规范