/* 【任務3】
(1)先建立一個Point(點)類,包含數據成員x,y(座標點);
(2)以Point爲基類,派生出一個Circle(圓)類,增加數據成員 (半徑);
(3)再以Circle類爲直接基類,派生出一個Cylinder(圓柱體)類,再增加數據成員h(高)。
要求編寫程序,設計出各類中基本的成員函數(包括構造函數、析構函數、修改數據成員和獲取數據成員的公共接口、用於輸出的重載運算符“<<”函數等),使之能用於處理以上類對象,最後求出圓格柱體的表面積、體積並輸出。
(提示:此任務可以分爲三個子任務分成若干步驟進行。先聲明基類,再聲明派生類,逐級進行,分步調試。——這種方法適用於做任何的項目)
(1)第1個程序: 基類Point類及用於測試的main()函數
(2)第2個程序:聲明Point類的派生類Circle及其測試的main()函數
(3)第3個程序:聲明Circle的派生類Cylinder及測試的main()函數
* 程序輸出: ......
* 程序頭部的註釋結束
*/
#include<iostream>
#include<Cmath>
#include<iomanip>
#define PI 3.1415926
using namespace std;
class Point //定義座標點類
{
public:
Point(){x = 0; y = 0;}
Point(double x0, double y0) {x = x0; y = y0;}
~Point(){}
double getx(){return x;}
double gety(){return y;}
friend ostream &operator << (ostream & input, Point & c);
protected:
double x, y; //點的橫座標和縱座標
};
ostream &operator << (ostream & output, Point & c)
{
output << "Point:(" << c.x << ", " << c.y << ")";
return output;
}
class Circle : public Point
{
public:
Circle(){r = 0;}
Circle(double x0, double y0, double r); //構造函數
~Circle(){};
double getr(){return r;}
friend ostream &operator << (ostream & out, Circle & c);
double perimeter0();
double area0();
protected:
double r;
};
Circle :: Circle(double x0, double y0, double r1) : Point(x0, y0), r(r1){} //構造函數
ostream &operator << (ostream & output, Circle & c)
{
output << "以" << "(" << c.getx() << "," << c.gety() << ")" << "爲圓心, " << "以" << c.r << "爲半徑的圓";
return output;
}
double Circle :: perimeter0()
{
return PI * 2 * r;
}
double Circle :: area0()
{
return PI * r * r;
}
class Cylinder : public Circle
{
public:
Cylinder(){height = 0;}
Cylinder(double x1,double y1, double r1, double h);
~Cylinder(){}
double area1();
double volume();
friend ostream &operator << (ostream & output, Cylinder & c);
protected:
double height;
};
Cylinder :: Cylinder(double x1,double y1, double r1, double h) : Circle(x1, y1, r1), height(h){}
ostream &operator << (ostream & output, Cylinder & c)
{
output << "以" << "(" << c.getx() << "," << c.gety() << ")" << "爲圓心, 以" << c.r << "爲半徑, 以" << c.height << "爲高的圓柱體";
return output;
}
double Cylinder :: area1()
{
return (area0() * 2 + perimeter0() * height);
}
double Cylinder :: volume()
{
return area0() * height;
}
int main()
{
Cylinder cy(3, 5, 6, 6);
cout << cy << endl;
cout << setiosflags(ios::fixed) << setprecision(3);
cout << "表面積是:" << cy.area1() << endl;
cout << "體積是:" << cy.volume() << endl;
system("pause");
return 0;
}
以(3,5)爲圓心, 以6爲半徑, 以6爲高的圓柱體
表面積是:452.389
體積是:678.584
請按任意鍵繼續. . .