寫一個程式,定義抽象型別Shape,由他派生三個類:Circle(圓形),Rectangle(矩形),Trapezoid(梯形),用一個函式printArea分別輸出三者的面積,3個圖形的資料在定義物件是給定。
uj5u.com熱心網友回復:
湊趣,湊趣class Shape
{
public:
virtual void printArea() = 0;
};
class Circle : public Shape
{
public:
Circle( float radius ) : _radius( radius ) { }
~Circle() { }
virtual void printArea() { cout << 3.1415 * ( _radius ^ 2 ) << endl; }
private:
float _radius;
};
class Rectangle : public Shape
{
public:
Rectangle( float length , float width ) : _length( length ) , _width( width ) { }
~Rectangle() { }
virtual void printArea() { cout << _length * _width << endl; }
private:
float _length;
float _width;
};
class Trapezoid : public Shape
{
public:
Trapezoid( float top , float bottom , float height ) : _top( top ) , _bottom( bottom ) , _height( height ) { }
~Trapezoid() { }
virtual void printArea() { cout << (_top + _bottom) * _height / 2 << endl; }
private:
float _top;
float _bottom;
float _height;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/77360.html
標籤:基礎類
上一篇:如何控制輸出字體變色
