继承与派生
定义一个point类,派生Rectangle类和Circle类,计算各派生类对象的面积Area().
#include<iostream> using namespace std; class point { protected: double x; double y; public: point(double X,double Y):x(X),y(Y) { } double getX() const { return x; } double getY() const { return y; } }; class Rectangle:public point { protected: double longth; double width; public: Rectangle(double X,double Y,double l,double w):point(X,Y),longth(l),width(w){ } double getArea() const { return longth*width; } }; class Circle:public point { protected: double r; public: Circle(double X,double Y,double R):point(X,Y),r(R){ } double getArea() const { return (3.14159*r*r); } }; int main() {Rectangle A(0,0,5,2); Circle B(0,0,2); cout<<"Rectangle area"<<A.getArea()<<endl; cout<<"Circle area"<<B.getArea()<<endl; return 0;
设计一个建筑物类Building,由它派生出教学楼TeachBuilding和宿舍楼类DormBuilding,前者包括教学楼编号,层数,教室数,总面积等基本信息,后者包括宿舍楼编号,层数,宿舍数,总面积和容纳学生总人数等基本信息。
1 #include<iostream> 2 using namespace std; 3 class Building 4 { 5 protected: 6 int number; 7 int floor; 8 double area; 9 public: 10 Building(int N,int F,double A):number(N),floor(F),area(A){ 11 } 12 int getnumber() const{ 13 return number;} 14 int getfloor() const{ 15 return floor;} 16 double getarea() const{ 17 return area;} 18 }; 19 class TeachBuilding:public Building{ 20 private: 21 int classroom; 22 public: 23 TeachBuilding(int N,int F,double A,int R):Building(N,F,A),classroom(R){ 24 25 } 26 int grtclassroom() const{ 27 return classroom;} 28 }; 29 class DormBuilding:public Building{ 30 private: 31 int dorm; 32 int student; 33 public: 34 DormBuilding(int N,int F,double A,int D,int S):Building(N,F,A),dorm(D),student(S){ 35 } 36 int getdorm() const{ 37 return dorm;} 38 int getstudent()const{ 39 return student;} 40 }; 41 int main() 42 { 43 TeachBuilding O(1,4,34,600); 44 DormBuilding E(2,5,23,400,64); 45 cout<<"TeachBuilding number="<<O.getnumber()<<" floor="<<O.getfloor()<<" classroom="<<O.grtclassroom()<<" area="<<O.getarea()<<endl; 46 cout<<"DormBuilding number="<<E.getnumber()<<" floor="<<E.getfloor()<<" dorm="<<E.getdorm()<<" area="<<E.getarea()<<" student="<<E.getstudent()<<endl; 47 return 0; 48 }