Hierarchy using private Data, and three-level Inheritance Hierarchy:
Circle类继承了Point类,而Cylinder类继承了Circle类,同时调用基类的构造函数,初始化数据
Circle具有Point的特性,Cylinder具有Circle的特性,形成了三级继承关系
base-class:
#ifndef POINT_H
#define
POINT_H
class
Point
{

public
:
Point(
int
=
0
,
int
=
0
);
//
默认构造函数
void
setX(
int
);
void
setY(
int
);
int
getX()
const
;
int
getY()
const
;
void
print()
const
;

//
private data.
private
:
int
x;
int
y;

}
;

#endif
#include
<
iostream
>
#include
<
iomanip
>
using
namespace
std;

#include
"
point.h
"
Point::Point(
int
xValue,
int
yValue )
:x( xValue ), y( yValue )

{
//
empty body
}
void
Point::setX(
int
xValue )

{
x
=
xValue;
}
void
Point::setY(
int
yValue )

{
y
=
yValue;
}
int
Point::getX()
const
{
return
x;
}
int
Point::getY()
const
{
return
y;
}
void
Point::print()
const
{
cout
<<
"
: [
"
<<
x
<<
"
,
"
<<
y
<<
"
]
"
;

}
derived-class:
#ifndef CIRCLE_H
#define CIRCLE_H

#include "point.h"

// inherited through public inheritance

class Circle : public Point
{

public:

Circle( int = 0, int = 0, int = 0 );

void setRadius( double );
double getRadius() const;

double getDiameter() const;
double getCircumference() const;
double getArea() const;

void print() const;

// private data
private:
double radius;

};

#endif

#include <iostream>
using namespace std;

#include "circle.h"

Circle::Circle( int xValue, int yValue, int radiusValue )
:Point( xValue, yValue ) // call base-class constructor.


{
setRadius( radiusValue );

}

void Circle::setRadius( double radiusValue )


{
radius = ( radiusValue < 0.0 ? 0.0 : radiusValue );

}

double Circle::getRadius() const


{
return radius;

}

double Circle::getDiameter() const


{
return 2 * getRadius();

}

double Circle::getCircumference() const


{
return 3.14159 * getDiameter();

}

double Circle::getArea() const


{
return 3.14159 * getRadius() * getRadius();

}

void Circle::print() const


{
cout << "Center = ";
Point::print();
cout << "; Radius = " << getRadius();

}

three-level Inheritance:
#ifndef CYLINDER_H
#define CYLINDER_H

#include "circle.h"


class Cylinder : public Circle
{

public:
Cylinder( int = 0, int = 0, double = 0.0, double = 0.0 );

void setHeight( double );
double getHeight() const;

double getArea() const;
double getVolumn() const;
void print() const;

private:
double height;

};

#endif

#include <iostream>
using namespace std;

#include "cylinder.h"

Cylinder::Cylinder( int xValue, int yValue, double radiusValue, double heightValue )
: Circle( xValue, yValue, radiusValue )


{
setHeight( heightValue );

}

void Cylinder::setHeight( double heightValue )


{
height = ( heightValue < 0.0 ? 0.0 : heightValue );

}

double Cylinder::getHeight() const


{
return height;

}

double Cylinder::getArea() const


{
return 2 * Circle::getArea() +
getCircumference() * getHeight();

}

double Cylinder::getVolumn() const


{
return Circle::getArea() * getHeight();

}

void Cylinder::print() const


{
Circle::print();
cout << "; Height = " << getHeight();

}
