1、1.#include class Dateint year;int month;int day;public:Date(int y, int m, int d)year = y;month = m;day = d;void Display()cout Type Sum(Type tArray, int iSize)2定义一个抽象类 CShape,它有一个纯虚函数 GetLength();派生出四边型类 CSquare 和圆类 CCircle,在派生类中重载函数 GetLength(),用于求图形的周长,编写测试程序进行测试。1参考程序: #include using namespace std
2、;template Type Sum(Type tArray, int iSize)Type tSum = 0;for (int i = 0; i using namespace std;class CShapepublic:virtual double GetLength() const = 0;class CSquare:public CShapepublic:CSquare(double dWidth, double dHeight)m_dWidth = dWidth;m_dHeight = dHeight;double GetLength() constreturn 2 * (m_dW
3、idth + m_dHeight);private:double m_dWidth, m_dHeight;class CCircle:public CShapepublic:CCircle(double dRadius)m_dRadius = dRadius;double GetLength() constreturn 3.1415926 * m_dRadius * m_dRadius;private:double m_dRadius;int main(void)CSquare oSquare(2, 3);cout / 预处理命令using namespace std; / 使用标准命名空间
4、stdconst double PI = 3.1415926; / 定义常量 PIclass Shapepublic:Shape() / 构造函数virtual Shape() / 析构函数virtual ShowArea() = 0; / 显示面积static double totalArea; / 总面积static void ShowTotalArea() cout using namespace std;class Rect private:double length, width; public: Rect(double l = 0, double w = 0): length(l)
5、, width(w) void Set(double l, double w) if (length = 50 | width = 50 ) throw “数据不在指定范围(0,50)!“; / 抛出异常length = l;width = w;double GetPerimeter() return 2 * (length + width); ;int main() try / 检查异常Rect obj(1, 8);cout using namespace std;class Vector2d double x, y; public: Vector2d(double a, double b)
6、: x(a), y(b) void Show() cout using namespace std;class Shapepublic:virtual double area() const =0; ;class Circle:public Shapepublic:Circle(double r):radius(r) virtual double area() const return 3.14159*radius*radius; protected:double radius; ;class Square:public Shapepublic:Square(double s):side(s)
7、 virtual double area() const return side*side; protected:double side;class Rectangle:public Shapepublic:Rectangle(double w,double h):width(w),height(h) virtual double area() const return width*height; protected:double width,height; ;class Trapezoid:public Shapepublic:Trapezoid(double t,double b,doub
8、le h):top(t),bottom(t),height(h)virtual double area() const return 0.5*(top+bottom)*height; protected:double top,bottom,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; ;int main()Circle circle(12.6); Square square(3.5); Rectangle rectangle(4.5,8.4); Trapezoid trapezoid(2.0,4.5,3.2); Triangle triangle(4.5,8.4); Shape *pt5= double areas=0.0; for(int i=0;iarea();cout“totol of all areas=“areasendl; return 0;