C++抽象类的使用问题!

定义一个抽象类Element,提供显示,求面积等公共接口(纯虚函数),然后派生出Point,Line,Circle等图形元素类,并定义这些虚函数!
程序代码:

#include<iostream>
#include<cmath>
using namespace std;
const double PI = 3.14159;
class Element{
public:
    virtual void Show()const=0;
    virtual double Area()const=0;
};
class Point:public Element{
protected:
    double x,y;
public:
    Point(): x(0), y(0) {}
    Point(double x, double y): x(x), y(y) {}
    void Show()const {
        cout << "x=" << x << ' ' << "y=" << y << endl;
    }
    double Area()const {
        return 0;
    }
    double Getx()const {
        return x;
    }
    double Gety()const {
        return y;
    }
};
class Circle:public Point{
protected:
    double radius;
public:
    Circle(): radius(0) {}
    Circle(double x,double y,double r):Point (x,y){
        radius = r;
    }
    Circle(const Circle &cir):Point (cir){
        radius = cir.radius;
    }
    void Show()const {
        Point::Show();
        cout << "radius=" << radius << endl;
    }
    double Area ()const {
        return PI * radius * radius;
    }

};
class Line:public Element{
protected:
    Point start,end;
public:
    Line() {}
    Line(double xv1, double yv1, double xv2, double yv2): start(xv1, yv1), end(xv2, yv2) {}
    double Area()const {
        return 0;

    }
    void Show()const {
        cout << "start point :\n";
        start.Show();
        cout << "end point\n";
        end.Show();
    }
    double GetLenth()const {
        double dx, dy;
        dx = start.Getx() - end.Getx();
        dy = start.Gety() - end.Gety();
        return sqrt(dx * dx + dy * dy);
    }
};

main函数的书写有讲究得重点突出基类指针指向派生类对象,并调用函数!

int main(){
    Element *p;
    Point point(3,4);
    Circle C(100,100,10);
    Line ln(0,0,100,100);
    p=&point;
    p->Show();
    cout<<"点面积"<<p->Area()<<endl;
    p=&C;
    p->Show();
    cout<<"圆面积"<<p->Area()<<endl;
    p=&ln;
    p->Show();
    cout << "线面积:" << p->Area()<< endl
         << "线长度:" << ln.GetLenth()<<endl;
    return 0;
}

注意,GetLenth()函数不是抽象类中的成员函数;调用不能用基类指针调用!

有收获的小伙伴别忘了点关注哦!

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值