天天看点

面向对象实验(七)——多态性2

理论

#include<bits/stdc++.h>
#define
using namespace std;
class Shape
{
    protected:
        int width,height;
    public:
        Shape(){}
        Shape(int a,int b):width(a),height(b){}
        void set_values(int a,int b){
            width=a;height=b;}
        virtual int area()=0;///纯虚函数
        ~Shape(){}
};
class circle:public Shape///圆
{
    public:
        circle(){}
        circle(int a,int b):Shape(a,b){}
        virtual int area(){
            return width*width*PI;}
};
class Rectangle:public Shape///矩形
{
    public:
        Rectangle(){}
        Rectangle(int a,int b):Shape(a,b){}
        virtual int area(){
            return width*height;}
        ~Rectangle(){}
};
class Triangle:public Shape///三角形
{
    public:
        Triangle(int a,int b):Shape(a,b){}
        virtual int area(){
            return width*height/2;}
        ~Triangle(){}
};

void Print_area(Shape& t1,Shape& t2,Shape& t3){
    Shape* p1=&t1;
    cout<<p1->area()<<endl;
    p1=&t2;
    cout<<p1->area()<<endl;
    p1=&t3;
    cout<<p1->area()<<endl;
}

int main(){

    Shape* p1;
    Rectangle rec_1(10,15);
    Triangle tri_1(10,6);
    circle cir_1(1,1);
    Print_area(rec_1,tri_1,cir_1);
    return 0;
}      

继续阅读