欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自定义图形层次系统

程序员文章站 2024-03-15 08:30:41
...
#include<iostream>
#include<iomanip>
const float pai=3.14;
using namespace std;
class Shape
{
public:
    virtual float has_s()=0;
    virtual float has_v()=0;
};
class Circle:public Shape
{
private:
    int r;
public:
    Circle(){}
    Circle(int x){r=x;}
    void input(int a){r=a;}
    virtual float has_s();
    virtual float has_v(){return 0;}
};
float Circle::has_s()
{
    return r*r*pai;
}
class Square:public Shape
{
private:
    int a;
public:
    Square(){}
    Square(int);
    void input(int x){a=x;}
    //virtual void input(int x)=0;
    virtual float has_s(){return a*a;}
    virtual float has_v(){return 0;}
    int get_a();
};
Square::Square(int x)
{
    a=x;
}
int Square::get_a()
{
    return a;
}
class Cube:public Square
{
public:
    Cube(){}
    Cube(int x):Square(x){}         //cube 和 square 之间赋值用构造函数还是成员函数input
    virtual float has_s()
    {
        int m=Square::get_a();
        return m*m*6;
    }
    virtual float has_v()
    {
        int n=Square::get_a();
        return n*n*n;
    }
    //Square input();
};
class Rectangle:public Shape
{
private:
    int a;
    int b;
public:
    Rectangle(){}
    Rectangle(int x,int y){a=x;b=y;}
    void input(int x,int y){a=x;b=y;}
    virtual float has_s(){return a*b;}
    virtual float has_v(){return 0;}
};
int main()
{
    Shape* p[4];
    cout<<"请输入圆的半径,它将也是正方形的边长、立方体的边长、矩形的宽"<<endl;
    int a;
    cin>>a;
    p[0]=new Circle(a);
    cout<<"s of a circle:"<<std::left<<setw(5)<<p[0]->has_s()<<" v of a circle:"<<p[0]->has_v()<<endl;
    p[1]=new Square(a);
    cout<<"s of a square:"<<std::left<<setw(5)<<p[1]->has_s()<<" v of a square:"<<p[1]->has_v()<<endl;
    p[2]=new Cube(a);
    cout<<"s of a cube:"<<std::left<<setw(5)<<p[2]->has_s()<<" v of a cube:"<<p[2]->has_v()<<endl;
    cout<<"请输入矩形的‘长’"<<endl;
    int b;
    cin>>b;
    p[3]=new Rectangle(a,b);
    cout<<"s of a rectangle:"<<std::left<<setw(5)<<p[3]->has_s()<<" v of a rectangle:"<<p[3]->has_v()<<endl;
    return 0;
    //int
    //p[1]

}

编写一个程序,定义抽象基类Shape,由它派生出3个派生类:Circle(圆形),Square(正方形),Rectangle(矩形)。Square正方形派生出了cube正方体。
用虚函数分别计算几种图形面积或体积,并求用基类指针数组,使它每一个元素指向一个派生类对象。

1.继承也可以有多继承,一个派生类继续向下继承,成为另一个类的基类。
这样情况下,最低端的的派生类仍可以拥有比其高几级的基类的成员,可以直接调用public部分,也含有基类私有成员。

2.多重继承运用纯虚函数要在基类中使用关键字virtual,并使函数=0,表明其在基类中不实现,如果其在派生类中也不实现,则也写成=0。

相关标签: cpp