#include "stdafx.h"
#include <iostream>
using namespace std;
const double PI = 3.1415926;
class Shape
{
public:
virtual double GetArea() = 0;
};
// 三角形
class Triangle
: public Shape
{
public:
// 含参构造
Triangle(double a, double b, double c)
: _a(a),
_b(b),
_c(c)
{
};
// 默认构造
Triangle()
: _a(0.0),
_b(0.0),
_c(0.0)
{
}
// 析构
~Triangle(){};
// 获取面积
virtual double GetArea()
{
double p=(_a+_b+_c)/2;
return sqrt(p*(p-_a)*(p-_b)*(p-_c));
}
// 重载操作符 <<
friend ostream& operator << (ostream& out, Triangle& triangle)
{
out<<"The three sides of the triangle is:"<<endl
<<"a="<<triangle._a<<endl
<<"b="<<triangle._b<<endl
<<"c="<<triangle._c<<endl;
return out;
};
// 重载操作符 >>
friend istream& operator >> (istream& in, Triangle& triangle)
{
cout<<"please input the three sides of the triangle:"<<endl;
in>>triangle._a
>> triangle._b
>> triangle._c;
return in;
};
private:
// 私有变量,三条边
double _a;
double _b;
double _c;
};
// 长方形
class Rectangle
: public Shape
{
public:
// 含参构造
Rectangle(double a, double b)
: _a(a),
_b(b)
{
};
// 默认构造
Rectangle()
: _a(0.0),
_b(0.0)
{
}
// 析构
~Rectangle(){};
// 获取面积
virtual double GetArea()
{
return _a*_b;
}
// 重载操作符 <<
friend ostream& operator << (ostream& out, Rectangle& rect)
{
out<<"The length and width of the rectangle is:"<<endl
<<"a="<<rect._a<<endl
<<"b="<<rect._b<<endl;
return out;
};
// 重载操作符 >>
friend istream& operator >> (istream& in, Rectangle& rect)
{
cout<<"please input the length and width of the rectangle:"<<endl;
in>>rect._a
>> rect._b;
return in;
};
private:
// 私有变量,两条边
double _a;
double _b;
};
// 圆形
class Circle
: public Shape
{
public:
// 含参构造
Circle(double r)
: _r(r)
{
};
// 默认构造
Circle()
: _r(0.0)
{
}
// 析构
~Circle(){};
// 获取面积
virtual double GetArea()
{
return PI*_r*_r;
}
// 重载操作符 <<
friend ostream& operator << (ostream& out, Circle& circle)
{
out<<"The radius of the circle is:"<<endl
<<"r="<<circle._r<<endl;
return out;
};
// 重载操作符 >>
friend istream& operator >> (istream& in, Circle& circle)
{
cout<<"please input the radius of the circle:"<<endl;
in>>circle._r;
return in;
};
private:
// 私有变量,半径
double _r;
};
int main()
{
Shape* pShape = new Triangle();
cin>>*(static_cast<Triangle*>(pShape));
cout<<*(static_cast<Triangle*>(pShape));
cout<<"The area is:"<<pShape->GetArea()<<endl;
delete pShape;
pShape = NULL;
pShape = new Rectangle();
cin>>*(static_cast<Rectangle*>(pShape));
cout<<*(static_cast<Rectangle*>(pShape));
cout<<"The area is:"<<pShape->GetArea()<<endl;
delete pShape;
pShape = NULL;
pShape = new Circle();
cin>>*(static_cast<Circle*>(pShape));
cout<<*(static_cast<Circle*>(pShape));
cout<<"The area is:"<<pShape->GetArea()<<endl;
delete pShape;
pShape = NULL;
return 0;
}
温馨提示:答案为网友推荐,仅供参考