1. 程式人生 > 其它 >南郵c++實驗三 容器類的V和S 問題程式碼

南郵c++實驗三 容器類的V和S 問題程式碼

技術標籤:南郵實驗c++

#include<iostream>
using namespace std;
const double PI = 3.14156;
class Container
{
protected:
	double radius;
public:
	Container(double r)
	{
		radius = r;
	}
	virtual double area() = 0;
	virtual double volume() = 0;
	virtual void print() = 0;
};
class Cube :public Container
{
public
: Cube(double r) :Container(r) {} double area() { return 6 * radius * radius; } double volume() { return radius * radius * radius; } void print() { double s, v; s = 6 * radius * radius; v = radius * radius * radius; cout << "正方體表面積是: " << s << endl; cout <<
"正方體體積是: " << v << endl; } }; class Sphere :public Container { public: Sphere(double r) :Container(r) {} double area() { return 4 * PI * radius * radius; } double volume() { return (radius * radius * radius * PI * 4) / 3; } void print() { double s, v; s = 4 * PI *
radius * radius; v = (radius * radius * radius * PI * 4) / 3; cout << "球體表面積是: " << s << endl; cout << "球體體積是: " << v << endl; } }; class Cylinder :public Container { protected: double height; public: Cylinder(double r, double h) :Container(r), height(h) {} double area() { return PI * radius * radius * 2 + 2 * PI * radius * height; } double volume() { return PI * radius * radius * height; } void print() { double s, v; s = PI * radius * radius * 2 + 2 * PI * radius * height; v = PI * radius * radius * height; cout << "圓柱體表面積是: " << s << endl; cout << "圓柱體體積是: " << v << endl; } }; int main() { Container* p; Cube a(4); Sphere b(4); Cylinder c(4, 4); p = &a; cout << p->area() << endl; cout << p->volume() << endl; p->print(); p = &b; cout << p->area() << endl; cout << p->volume() << endl; p->print(); p = &c; cout << p->area() << endl; cout << p->volume() << endl; p->print(); return 0; }