涉及到C++的類構造函數以及析構函數的一些基本概念,附上個人分析,可能有錯誤,還望不吝指出。
代碼如下:
#include <iostream>
using namespace std;
class BB{
private:
int data;
public:
BB(){
cout<<"default constructor"<<endl;
}
~BB(){
cout<<"destructed"<<endl;
}
BB(int i):data(i){
cout<<"constructed by "<<data<<endl;
}
BB(BB &b){
cout<<"test"<<endl;
};
BB &operator=(BB &b){
cout<<"test ="<<endl;
return b;
}
};
BB Play(BB b){
return b;
}
int main(int argc, char *argv[])
{
BB temp;
temp=Play(5);
return 0;
}
分析如下:
default constructor:調用temp無參數構造函數
constructed by 5:5隱式轉換,調用BB::BB(int)
test:Play返回的時候相當於語句BB xx=b;調用拷貝構造函數
destructed:返回值構造完畢,銷燬b
test =:temp=xx;因爲temp已經構造完畢,這裏只是調用賦值函數
destructed:調用完temp=xx;銷燬xx,因爲xx只是屬於Play函數的一部分,執行返回後的下一條語句前就會被銷燬
destructed:main函數返回,temp被銷燬