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++编译: