1、第六章课后习题答案(第二版谭浩强)1:/xt6-1/cpp#include /如用 VC+应改为#include using namespace std; /如用 VC+应取消此行#include “cylinder.h“#include “point.cpp“#include “circle.cpp“#include “cylinder.cpp“int main()Cylinder cy1(3.5,6.4,5.2,10);coutusing namespace std;class Pointpublic:Point(float a,float b):x(a),y(b)Point()coutu
2、sing namespace std;class Pointpublic:Point(float a,float b):x(a),y(b)Point()coutusing namespace std;class Pointpublic:Point(float a,float b):x(a),y(b)virtual Point()coutusing namespace std;/定义抽象基类 Shapeclass Shapepublic:virtual double area() const =0; /纯虚函数;/定义 Circle 类class Circle:public Shapepubli
3、c:Circle(double r):radius(r) /结构函数virtual double area() const return 3.14159*radius*radius; /定义虚函数protected:double radius; /半径;/定义 Rectangle 类class Rectangle:public Shapepublic:Rectangle(double w,double h):width(w),height(h) /结构函数virtual double area() const return width*height; /定义虚函数protected:doubl
4、e width,height; /宽与高;class Triangle:public Shapepublic:Triangle(double w,double h):width(w),height(h) /结构函数virtual double area() const return 0.5*width*height; /定义虚函数protected:double width,height; /宽与高;/输出面积的函数void printArea(const Shape /定义抽象基类 Shapeclass Shapepublic:virtual double area() const =0;
5、/纯虚函数;/定义 Circle(圆形 )类class Circle:public Shapepublic:Circle(double r):radius(r) /结构函数virtual double area() const return 3.14159*radius*radius; /定义虚函数protected:double radius; /半径;/定义 Square(正方形)类class Square:public Shapepublic:Square(double s):side(s) /结构函数virtual double area() const return side*sid
6、e; /定义虚函数protected:double side;/定义 Rectangle(矩形)类class Rectangle:public Shapepublic:Rectangle(double w,double h):width(w),height(h) /结构函数virtual double area() const return width*height; /定义虚函数protected:double width,height; /宽与高;/定义 Trapezoid(梯形)类class Trapezoid:public Shapepublic:Trapezoid(double t,
7、double b,double h):top(t),bottom(t),height(h) /结构函数virtual double area() const return 0.5*(top+bottom)*height; /定义虚函数protected:double top,bottom,height; /上底、下底与高;/定义 Triangle(三角形) 类class Triangle:public Shapepublic:Triangle(double w,double h):width(w),height(h) /结构函数virtual double area()const return
8、 0.5*width*height; /定义虚函数protected:double width,height; /宽与高;int main()Circle circle(12.6); /建立 Circle 类对象circleSquare square(3.5); /建立 Square 类对象 squareRectangle rectangle(4.5,8.4); /建立 Rectangle 类对象 rectangleTrapezoid trapezoid(2.0,4.5,3.2); /建立 Trapezoid 类对象 trapezoidTriangle triangle(4.5,8.4); /建立 Triangle 类对象Shape *pt5= /定义基类指针数组 pt,使它每一个元素指向一个派生类对象double areas=0.0; /areas 为总面积for(int i=0;iarea();cout“totol of all areas=“areasendl; /输出总面积return 0;