一、示例对象数组:
#include<iostream>
using namespace std;class Point{private:int x,y;public:Point(int px=0,int py=0){x=px;y=py;}void init(int px=0,int py=0){x=px;y=py;}void print(){cout<<"("<<x<<","<<y<<")"<<endl;}
};int main(){Point *pArray=new Point[5];if(!pArray){cout<<"allocation error!"<<endl;return -1;}int x,y,k;for(k=0;k<5;k++){cin>>x>>y;pArray[k].init(x,y);}cout<<"Array of Point:"<<endl;for(k=0;k<5;k++){pArray[k].print();}delete[]pArray;return 0;
}
说明:
在执行“Point *pArray=new Point[5];”语句时,系统自动调用构造函数五次,按默
认值初始化动态声明五个对象。
二、示例类的组合:
#include<iostream>
#include<cmath>
using namespace std;class Point{private:int x;int y;public:Point(int px,int py){x=px;y=py;}void print(){cout<<"("<<x<<","<<y<<")"<<endl;}friend class Triangle;
}; class Triangle{private:Point p1,p2,p3;public:Triangle(Point xp1,Point xp2,Point xp3):p1(xp1),p2(xp2),p3(xp3){}double GetArea();void display();
};double Triangle::GetArea(){double x1=p1.x-p2.x;double y1=p1.y-p2.y;double x2=p1.x-p3.x;double y2=p1.y-p3.y;double x3=p2.x-p3.x;double y3=p2.y-p3.y;double L1=sqrt(x1*x1+y1*y1);double L2=sqrt(x2*x2+y2*y2);double L3=sqrt(x3*x3+y3*y3);double s=(L1+L2+L3)/2;return sqrt(s*(s-L1)*(s-L2)*(s-L3));
}void Triangle::display(){cout<<"the Point of Tiangle are:"<<endl;p1.print();p2.print();p3.print();
}int main(){Point p1(3,4),p2(4,5),p3(3,9);Triangle t(p1,p2,p3);t.display();cout<<"三角形面积:"<<t.GetArea()<<endl; return 0;
}
说明:
Triangle是Point的组合类,里面包含三个Point对象。为了便于计算三角形边长(两点的距离),将Triangle声明为Point的友元类,这样就可以方便地访问Point类中的私有成员x和y。计算三角形面积时用到了已知三边边长求面积的海伦公式。