您好,欢迎访问三七文档
声明一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有GetArea//定义一个Shape基类,在此基础上派生出Rectangle和Circle类,二者都有GetArea()函数计算对象的面积。//使用Rectangle类创建一个派生类Square。并应用相应类的对象测试。#includeiostream.hclassShape{public:Shape(){}~Shape(){}virtualfloatGetArea()const{return-1;}};classCircle:publicShape{public:Circle(floatr):radius(r){}~Circle(){};floatGetArea(){return3.14f*radius*radius;}private:floatradius;};classRectangle:publicShape{public:Rectangle(floatlen,floatwidth):m_len(len),m_width(width){}~Rectangle(){}floatGetArea(){returnm_len*m_width;}floatGetLength(){returnm_len;}floatGetWidth(){returnm_width;}private:floatm_len,m_width;};classSquare:publicRectangle{public:Square(floatlen);~Square(){}};Square::Square(floatlen):Rectangle(len,len){}voidmain(){Shape*sp;sp=newCircle(5);coutTheareaofthecircleissp-GetArea()endl;deletesp;sp=newRectangle(4,6);coutTheareaoftherectangleissp-GetArea()endl;deletesp;sp=newSquare(5);coutTheareaoftheSquareissp-GetArea()endl;deletesp;}
本文标题:声明一个基类Shape-在此基础上派生出Rectangle和Circle-二者都有GetArea
链接地址:https://www.777doc.com/doc-5339912 .html