(1)先建立一个Point(点)类,包含数据成员x,y(坐标点);
(2)以Point为基类,派生出一个Circle(圆)类,增加数据成员 (半径);
(3)再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高)。要求编写程序,设计出各类中基本的成员函数(包括构造函数、析构函数、修改数据成员和获取数据成员的公共接口、用于输出的重载运算符“<<”函数等),使之能用于处理以上类对象,最后求出圆格柱体的表面积、体积并输出。
#include<iostream>
#define pi 3.1415
using namespace std;
class Point
{
public:
int x;
int y;
//public:
Point (int xx = 0, int yy = 0):x(xx), y(yy){};
~Point();
void setPoint(int a, int b);
friend ostream & operator << (ostream & out, Point &a);
};
Point::~Point ()
{
}
ostream & operator << (ostream & out, Point & a)
{
out << "(" << a.x << "," << a.y << ")" << endl;
return out;
}
void Point::setPoint (int a, int b)
{
x = a;
y = b;
}
class Circle: public Point
{
public:
int r;
public:
Circle (int xx, int yy, int r1):Point (xx, yy){r = r1;}
~Circle();
void setCircle(int a, int b, int c);
friend ostream & operator << (ostream & out, Circle & a);
};
Circle::~Circle()
{
}
void Circle::setCircle(int a, int b, int c)
{
x = a;
y = b;
r = c;
}
ostream & operator << (ostream & out, Circle & a)
{
out << "圆心:"<< "(" << a.x << "," << a.y << ")" << endl;
out << "半径:" << a.r;
return out;
}
class Cylinder: public Circle
{
private:
int h;
public:
Cylinder(int xx, int yy, int r1, int h1):Circle(xx, yy, r1){h = h1;}
~Cylinder();
void setCylinder(int a, int b, int c, int d);
friend ostream & operator << (ostream &out, Cylinder &a);
double Carea();
double Cvolume();
};
Cylinder::~Cylinder()
{
}
void Cylinder::setCylinder(int a, int b, int c, int d)
{
x = a;
y = b;
r = c;
h = d;
}
ostream & operator << (ostream &out, Cylinder &a)
{
out <<"圆心:" << "("<< a.x <<"," <<a.y <<")" << endl;
out<<"半径:" << a.r << endl;
out<< "高: " << a.h << endl;
return out;
}
double Cylinder::Carea()
{
double m;
m = 2 * r * pi;
return (m * h);
}
double Cylinder::Cvolume()
{
return (r * r * pi * h);
}
int main()
{
Cylinder c(2, 2, 2 ,2);
cout << c;
cout<< "表面积:" << c.Carea () << endl;
cout << "体积:" << c.Cvolume () << endl;
system("pause");
return 0;
}
没有基类的许可,子类是不可以使用基类的数据的,保护自己的隐私!