Line類調用Point類的兩個對象p1,p2作為其數據成員,計算線段長度
組合類構造函數定義的一般形式為:
類名::類名(形參表):內嵌對象1(形參表),內嵌對象2(形參表)... {類的初始化}
Line例子(課本例子學習):
1 #include<iostream> 2 #include<cmath> 3 using namespace std; 4 class Point{ 5 public: 6 //隱式內聯構造函數(顯示inline) 7 Point(int newX,int newY){ 8 x=newX; 9 y=newY; 10 } 11 //復制構造函數 12 Point(Point &p); 13 int getX(){return x;} 14 int getY(){return y;} 15 private: 16 int x,y; 17 18 }; 19 //復制構造函數的實現 20 Point::Point(Point &p){ 21 x=p.x; 22 y=p.y; 23 } 24 25 //類的組合 26 class Line{ 27 public: 28 Line(Point xp1,Point xp2); 29 Line(Line &q); 30 double getLen(){return len;} 31 private: 32 Point p1,p2; 33 double len; 34 }; 35 //組合類的構造函數 36 Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){ 37 double x=static_cast<double>(p1.getX()-p2.getX()); 38 double y=static_cast<double>(p1.getY()-p2.getY()); 39 len=sqrt(x*x+y*y); 40 } 41 //組合類的復制構造函數 42 Line::Line(Line &q):p1(q.p1),p2(q.p2){ 43 cout<<"calling the copy construct of Line"<<endl; 44 len=q.len; 45 } 46 47 void fun1(Point p){ 48 cout<<"fun1:"<<p.getX()<<","<<p.getY()<<endl; 49 } 50 Point fun2(){ 51 Point a(1,2); 52 return a; 53 } 54 int main(){ 55 //Point 56 Point a(8,9); 57 Point b=a; 58 cout<<"test point:x="<<b.getX()<<endl; 59 fun1(b); 60 b=fun2(); 61 cout<<"test point:x="<<b.getX()<<endl; 62 //Line 63 //point類的復制構造函數被調用了6次 64 //兩個對象在Line構造函數進行函數參數形實參結合時+初始化內嵌對象時+復制構造line2時被調>用 65 cout<<"------------"<<endl; 66 Point m(3,4),n(5,6); 67 Line line(m,n); 68 cout<<"line:"<<line.getLen()<<endl; 69 Line line2(line); 70 cout<<"line2:"<<line2.getLen()<<endl; 71 72 return 0; 73 }
運行結果Ubuntu下g++編譯: