C++ 定義一個基類Shape,在此基礎上派生出Rectangle和Circle,二者都有getArea()函數計算對象面積。使用Rectangle類創建一個派生類Square。

定義一個基類Shape,在此基礎上派生出Rectangle和Circle,二者都有getArea()函數計算對象面積。使用Rectangle類創建一個派生類Square。

注:圓周率取3.14

//
//  main.cpp
//  week6homework
//
//  Created by Noki on 2020/3/29.
//  Copyright © 2020 Noki. All rights reserved.
//

#include <iostream>
#include <cmath>
using namespace std;

class Shape{
public:
    virtual double getarea()=0;
    virtual double getperi()=0;
};

class Rectangle:public Shape{
public:
    Rectangle(float a, float b):length(a),width(b){}
    double getarea(){
        return length*width;
    }
    double getperi(){
        return 2*(length+width);
    }
private:
    float length, width;
};

class Circle:public Shape{
public:
    Circle(float r):radius(r){}
    double getarea(){
        return 3.14*pow(radius,2);
    }
    double getperi(){
        return 2*3.14*radius;
    }
private:
    float radius;
};

class Square: public Rectangle{
public:
    Square(float a): Rectangle(a, a){}
};

int main() {
    float a,b,r;
    cout<<"Input a,b:";
    cin>>a>>b;
    cout<<"Input r:";
    cin>>r;
    Rectangle rec(a,b);
    Circle cir(r);
    cout<<"Rectangl Area:"<<rec.getarea()<<',';
    cout<<"Circle Area:"<<cir.getarea()<<endl;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章