Jurous
2020-06-15 17:44
采纳率: 63.6%
浏览 143

有大佬帮忙看看这个怎么写吗

声明一个Shape抽象类,在此基础上派生出Rectangle(矩形)和Circle(圆)类;
二者都有GetArea( )函数计算对象的面积,GetPerim( )函数计算对象的周长。
要求:请使用基类引用调用虚函数方法,实现动态多态

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • qtchen_1988 2020-06-15 18:58
    已采纳
    #include <iostream>
    #define _USE_MATH_DEFINES
    #include <math.h>
    using namespace std;
    
    class Shape{
    public:
        virtual double GetArea()=0;
        virtual double GetPerim()=0;
    };
    class Rectangle:public Shape{
    public:
        Rectangle(double length,double width):mLength(length),mWidth(width){}
        virtual double GetArea(){
            return mLength*mWidth;
        }
         virtual double GetPerim(){
            return (mLength+mWidth)*2;
        }
    private:
        double mLength;
        double mWidth;
    };
    
    class Circle:public Shape{
    public:
        Circle(double r):mR(r){}
        virtual double GetArea(){
            return M_PI*mR*mR;
        }
        virtual double GetPerim(){
           return mR*2*M_PI;
       }
    private:
        double mR;
    };
    
    int main()
    {
        Rectangle rect(12.8,6);
        Circle cle(4.5);
        Shape *sh = &rect;
        std::cout<<sh->GetArea()<<std::endl;
        std::cout<<sh->GetPerim()<<std::endl;
        std::cout<<"***************************"<<std::endl;
        sh = &cle;
        std::cout<<sh->GetArea()<<std::endl;
        std::cout<<sh->GetPerim()<<std::endl;
        return 0;
    }
    
    
    点赞 评论

相关推荐 更多相似问题