通俗的解釋就是元素構成小模塊,小模塊構成大模塊。
析構的過程正好相反,大模塊析構後小模塊被暴露,小模塊再被析構
要注意:先構造的後析構
#include <bits/stdc++.h>
using namespace std;
class Point{///定義一個類對象相當於一個模塊
private:
int x,y;///類對象的數據成員,對外不可見
public:///類對象的對外接口
///構造函數:與類同名,初始化對象的數據成員,使得小模塊形成完整模塊
Point(int px,int py):x(px),y(py){
cout<<"普通構造函數生成"<<this<<endl;;
ShowPoint();
}
///拷貝構造函數:完成完整模塊之間的複製
Point(Point& p):x(p.x),y(p.y){
cout<<"拷貝構造函數生成"<<this<<endl;
ShowPoint();
}
void ShowPoint(){ cout<<"("<<x<<","<<y<<")"<<this<<endl;}
int getx(){return x;}
int gety(){return y;}
~Point(){cout<<"析構函數調用"<<this<<endl;}
};
class Line{
private:
Point p1;
Point p2;
double len;
public:
///pa->xp1 pb->xp2 拷貝構造函數
///xp1->p1 xp2->p2 拷貝構造函數
/*Line(Point xp1,Point xp2):p1(xp1),p2(xp2){///構造函數
cout<<"Line的構造函數"<<this<<endl;
};
Line(Line &L):p1(L.p1),p2(L.p2){
cout<<"Line的拷貝構造函數"<<this<<endl;
}*/
Line(Point xp1,Point xp2);
Line(Line &L);
~Line(){cout<<"Line的析構函數"<<this<<endl;}
double getlen() {return len;}
};
///::預作用符 表示Line屬於Line類
///內聯函數:class內必須聲明才能使用
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){
cout<<"Line的構造函數"<<this<<endl;
double x=p1.getx()-p2.getx();
double y=p1.gety()-p2.gety();
len=sqrt(x*x+y*y);
}
///p1(L.p1)調用Point的拷貝構造函數
Line::Line(Line &L):p1(L.p1),p2(L.p2){
cout<<"Line的拷貝構造函數"<<this<<endl;
}
void ShowPointInfo(Point p){
cout<<"ShowPointInfo begin"<<endl;
p.ShowPoint() ;
cout<<"ShowPointInfo end"<<endl;
}
///加Line的拷貝構造函數L2(L1)
int main(){
/*Point pa(3,4);
ShowPointInfo(pa);
cout<<endl;*/
Point pa(3,4);
Point pb(10,9);
Line L1(pa,pb);
cout<<"L2***********"<<endl;
Line L2(L1);
/*cout<<"L1 start point:";
pa.ShowPoint();
puts("");
cout<<"L1 end point:";
pb.ShowPoint();
puts("");
cout<<"The lengh of L1 is:"<<L1.getlen()<<endl;*/
return 0;
}
/**以下結合this指針分析程序執行過程
運行結果:
普通構造函數生成0x6dfec8 ->根據參數構造pa
(3,4)0x6dfec8
普通構造函數生成0x6dfec0 ->根據參數構造pb
(10,9)0x6dfec0
拷貝構造函數生成0x6dfed0 ->根據pb生成xp2
(10,9)0x6dfed0
拷貝構造函數生成0x6dfed8 ->根據pa生成xp1
(3,4)0x6dfed8
拷貝構造函數生成0x6dfea8 ->根據xp1生成p1
(3,4)0x6dfea8
拷貝構造函數生成0x6dfeb0 ->根據xp2生成p2
(10,9)0x6dfeb0
Line的構造函數0x6dfea8 ->構造出L1
析構函數調用0x6dfed8 ->L1構造完成,xp1析構
析構函數調用0x6dfed0 ->xp2析構
L2*********** ->以下爲L2的拷貝構造
拷貝構造函數生成0x6dfe90 ->根據L1.p1構造L2的p1
(3,4)0x6dfe90
拷貝構造函數生成0x6dfe98 ->根據L1.p2構造L2的p2
(10,9)0x6dfe98
Line的拷貝構造函數0x6dfe90 ->L2拷貝構造成功
Line的析構函數0x6dfe90 ->L2析構
析構函數調用0x6dfe98 ->L2.p2析構
析構函數調用0x6dfe90 ->L2.p1析構
Line的析構函數0x6dfea8 ->L1析構
析構函數調用0x6dfeb0 ->L1.p2析構
析構函數調用0x6dfea8 ->L1.p1析構
析構函數調用0x6dfec0 ->pa析構
析構函數調用0x6dfec8 ->pb析構
**/