acm-抽象基类

/*
*程序的版权和版本声明部分:
*Copyright(c)2014,烟台大学计算机学院学生
*All rights reserved.
*文件名称:
*作者:田成琳
*完成日期:2014 年 5 月 28 日
*版本号:v1.0
*对任务及求解方法的描述部分:
*问题描述:编写一个程序,声明抽象基类Shape,由它派生出3个派生类: Circle、Rectangle、Triangle,
           用一个函数printArea分别输出以上三者的面积,3个图形的数据在定义对象时给定。
*输入描述: Input
           圆的半径
           矩形的边长
           三角形的底与高
*程序输出:Output
           圆的面积
           矩形的面积
           三角形的面积
*问题分析:
*算法设计:
*/
#include<iostream>
#include<iomanip>
using namespace std;
class Shape
{
public:
	virtual double Area()=0;
};
class Circle:public Shape
{
public:
	Circle(double R):r(R){}
	virtual double Area()
	{
		return 3.1415926*r*r;
	}
private:
	double r;
};
class Rectangle:public Shape
{
public:
	Rectangle(double a,double b):length(a),width(b){};
	virtual double Area()
	{
		return length*width;
	}
private:
	double length,width;
};
class Triangle:public Shape
{
public:
    Triangle(double a,double b):di(a),height(b){};
	virtual double Area()
	{
		return di*height/2;
	}
private:
	double di,height;
};
void printArea(Shape& shape)
{
    cout<<shape.Area()<<endl;
}
int main()
{
    float r,a,b,w,h;
    cout<<fixed<<setprecision(2);
    cin>>r;
    Circle circle(r);
    cout<<"area of circle = ";
    printArea(circle);//printArea()是普通函数,不在类内!!
    cin>>a>>b;
    Rectangle rectangle(a,b);
    cout<<"area of rectangle = ";
    printArea(rectangle);
    cin>>w>>h;
    Triangle triangle(w,h);
    cout<<"area of triangle = ";
    printArea(triangle);
    return 0;
}


运行结果:

心得体会:这个题很有借鉴意义啊,这几天做惯了类内函数,今天这个题突然那个printArea()是普通函数,弄的一时竟手无足错。

抽象类内应是求面积的纯虚函数,一开始我竟然写了void printArea()函数~~糗大

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值