C++類的組合


:都說書寫是為了更好地思考,最近在學習c++編程設計,之前在博客園上看到的各位大神們的隨筆,心中充滿各種羡慕嫉妒,怎么都寫得這么好。為此在摸索良久后,終於在今天開啟了自己的隨筆之路。
正文:c++類的組合,描述的是一個類內嵌入其他類的對象作為成員的情況,它們之間的關系式包含與被包含的關系。當創建類的時候,如果這個類具有內嵌對象成員,那么各個內嵌對象也將被自動創建。  在聲明一個組合類的對象時,不僅它自身的構造函數將被調用,而且還將調用其內嵌對象的構造函數。構造函數的調用順序為:

①按照內嵌對象在組合類的聲明出現的次序,依次調用其內嵌對象的構造函數。

②執行本類構造函數的函數體。

 實例:求兩點間的距離(開發環境:VS2010 控制台應用程序)

 

 1 #include "stdafx.h"
 2 #include<iostream>
 3 #include<math.h>
 4 using namespace std;
 5 class Point //定義Point類
 6 {
 7 public: 
 8     Point(float x,float y);//構造函數
 9     Point(Point& point);//拷貝構造函數
10     float GetX(){return X;}
11     float GetY(){return Y;}
12 private:
13     float X,Y;
14 
15 };
16 Point::Point(float x,float y):X(x),Y(y)
17 {
18  cout<<"Point類構造函數被調用"<<endl;
19 }
20 
21 Point::Point(Point& point)
22 {
23     X=point.X;
24     Y=point.Y;
25     cout<<"Point類拷貝構造函數被調用:"<<endl;
26 }
27 
28 class Distance
29 {
30 public:
31     Distance(Point p1,Point p2);//構造函數
32     double Get_Dis(){return dist;}
33 private:
34     Point P1,P2;
35     double dist;
36 
37 };
38 Distance::Distance(Point p1,Point p2):P1(p1),P2(p2)
39 {
40    cout<<"Distance類構造函數被調用"<<endl;
41    double x=double(P1.GetX()-P2.GetX());
42    double y=double(P1.GetY()-P2.GetY());
43    dist=sqrt(x*x+y*y);
44 }
45 
46 int _tmain(int argc, _TCHAR* argv[])
47 {
48     float x1,y1,x2,y2;
49     cout<<"請輸入第一個點坐標值(x,y):"<<endl;
50     cin>>x1>>y1;
51     cout<<"請輸入第二個點坐標值(x,y):"<<endl;
52     cin>>x2>>y2;
53     Point p1(x1,y1),p2(x2,y2);
54     Distance dis(p1,p2);
55     cout<<"此兩點距離為:"<<dis.Get_Dis()<<endl;
56     system("pause");
57     return 0;
58 }

 程序運行結果為:

分析:主程序在執行時,首先生成兩個Point類對象,然后構造Distance類對象,在執行第54行代碼時(即聲明Distance類對象),Point類的拷貝構造函數被調用了4次,它們分別是兩個Point對象在Distance類對象構造函數進行函數參數形參與實參結合時初始化內嵌對象時調用的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM