#include <iostream>
using std::cout;
using std::endl;
const static double PI =3.1415926;
class Point
{
public:
Point(float x1 = 0, float y1 = 0,float z1 = 0)
: x(x1), y(y1), z(z1)
{}
float getX() const
{ return x; }
float getY() const
{ return y; }
float getZ() const
{ return z;}
protected:
float x;
float y;
float z;
};
class Circle : public Point
{
public:
Circle( float r = 0,float x = 0, float y = 0 ,float z = 0 );
float getZ() const
{ return z;}
float area ( ) const { return PI*PI*radius; }
//protected:
float radius;
float y;
float z;
};
Circle::Circle( float r,float x, float y,float z ) : radius(r)
{
this->x = x; this->y = y; this->z = z; // 子类没有的,就调用父类的
}
class Car
{
};
void main()
{
Point *p, pt(11,22,33);
Circle *pc, pr(10,77,88,99 );
cout << "derive class' X =" << pr.getX()
<<" :Y =" << pr.getY()
<<" :Z ="<< pr.getZ() << endl; // 77,0
cout << " derive y,z" << pr.y << ":" <<pr.z << endl;
//把派生类Circle对象的地址赋给了基类指针p
p = & pr; // 77,0
cout << "base class' X =" << p ->getX()
<< " :Y ="<< p->getY()
<< " :z ="<< p->getZ() << endl;
cout << "area = " << pr.area() << endl;
//cout << "area = " << p->area() << endl;//“area”: 不是“Point”的成员
//cout << "" << p->
// p->area(); // error
// 基类到派生类
// pc = &pt; // error 无法从“Point *”转换为“Circle *”
// 原因:基类并不知道自己是否有派生类,它不知道他内存的后面是不是派生类对象
// 而派生类->基类时,因为派生类必须先构造基类,它知道基类一定存在(?抽象类)
//把基类指针强制转换为派生类指针
pc = (Circle *) p;
cout <<"把基类指针强制转换为派生类指针" << pc->area() << endl;
p = &pt;
pc = (Circle *) p;
cout << "把基类指针强制转换为派生类指针" << pc->area() << endl;
//cout << pc->radius << endl; //
// 派生指针转化为基指针
Car * car;
pc =(Circle *) car;
//cout << pc->area() << endl;
}
@font-face{ font-family:"Times New Roman"; } @font-face{ font-family:"宋体"; } @font-face{ font-family:"Symbol"; } @font-face{ font-family:"Arial"; } @font-face{ font-family:"黑体"; } @font-face{ font-family:"Courier New"; } @font-face{ font-family:"Wingdings"; } @font-face{ font-family:"新宋体"; } p.0{ margin:0pt; margin-bottom:0.0001pt; layout-grid-mode:char; text-align:justify; font-size:10.5000pt; font-family:'Times New Roman'; } div.Section0{ margin-top:72.0000pt; margin-bottom:72.0000pt; margin-left:90.0000pt; margin-right:90.0000pt; size:612.0000pt 792.0000pt; }
程序进行结果
derive class' X =77 :Y =0 :Z =99
derive y,z88:99
base class' X =77 :Y =0 :z =0
area = 98.696
把基类指针强制转换为派生类指针98.696
把基类指针强制转换为派生类指针5.87419e-038