美文网首页
C++继承练习5

C++继承练习5

作者: 科学旅行者 | 来源:发表于2016-12-14 15:56 被阅读24次

    参考资料:《C++Primer习题集(第5版)》

    目的:练习继承层次的构造。

    #include <iostream>
    #include <algorithm>
    #include <string>
    using namespace std;
    
    class Figure {//公共基类, 表示几何图元;
        public:
            Figure() = default;//默认构造函数;
            Figure(double x, double y) : xSize(x), ySize(y) {}//构造函数;
            virtual ~Figure() = default;//虚析构函数;//解决动态绑定时的释放问题; 
        protected:
            double xSize, ySize;//图元的尺寸;
    };
    
    class Figure_2D : public Figure {//求平面图形的抽象基类;//该类也是Figure的派生类;
        public:
            Figure_2D(double x, double y) : Figure(x, y) {}//调用基类的构造函数;
            virtual double area() = 0;//求面积操作, 纯虚函数;
            virtual double perimeter() = 0;//求周长操作, 纯虚函数;       
    };
    
    class Figure_3D : public Figure {//求空间图形的抽象基类;//该类也是Figure的派生类;
        public:
            Figure_3D(double x, double y, double z) : Figure(x, y), zSize(z) {}//调用基类的构造函数;
            virtual double cubage() = 0;//求体积操作, 纯虚函数;
        protected:
            double zSize;//三维空间的z轴;
    };
    
    class Rectangle : public Figure_2D {//派生类, 矩形;
        public:
            Rectangle(double x, double y) : Figure_2D(x, y) {}//构造函数;
            virtual double area() override {//重写, 求矩形面积;
                return xSize * ySize;
            }
            virtual double perimeter() {//重写, 求矩形周长;
                return 2 * (xSize + ySize);
            }
    };
    
    class Circle : public Figure_2D {//派生类, 圆;
        public:
            Circle(double x, double y) : Figure_2D(x, y) {}//构造函数;
            virtual double area() override {//重写, 求圆面积;
                return 3.1415926 * xSize * xSize;//假定xSize = ySize = 圆的半径;
            }
            virtual double perimeter() {//重写, 求圆周长;
                return 2 * 3.1415926 * xSize;//假定xSize = ySize = 圆的半径;
            }
    };
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(NULL);
        Rectangle *r = new Rectangle(4, 5);
        cout << r -> area() << endl;
        cout << r -> perimeter() << endl;
        Circle *c = new Circle(2, 2);
        cout << c -> area() << endl;
        cout << c -> perimeter() << endl;
        delete c;
        delete r;   
        return 0;
    }
    /*
    20
    18
    12.5664
    12.5664
    */
    

    相关文章

      网友评论

          本文标题:C++继承练习5

          本文链接:https://www.haomeiwen.com/subject/piwimttx.html