test.h
#ifndef TEST
#define TEST
#include<iostream>
using namespace std;
class Shape//抽象基类,包含一个或一个以上纯虚函数
{
private:
/* data */
public:
virtual float area() const {return 0.0;}//虚函数
virtual float volume() const {return 0.0;}//虚函数
virtual void shapeName() const=0;//纯虚函数
};
class Point:public Shape//point 是Shape的公用派生类
{
private:
/* data */
protected:
float x,y;
public:
Point(float=0,float=0);
void setPoint(float,float);
float getX() const {return x;}
float getY() const {return y;}
virtual void shapeName() const {cout<<"Point:";}
friend ostream & operator<<(ostream &,const Point &);//运算符重载
};
class Circle:public Point
{
private:
/* data */
protected:
float radius;
public:
Circle(float x=0,float y=0,float r=0);
void setRadius(float);
float getRaidus() const;
virtual float area() const;
virtual void shapeName() const {cout<<"Circle:";}
friend ostream& operator<<(ostream& ,const Circle&);
};
class Cylinder:public Circle
{
private:
/* data */
protected:
float height;
public:
Cylinder(float x=0,float y=0,float r=0,float h=0);
void setHight(float);
virtual float area() const;
virtual float volume() const;
virtual void shapeName() const {cout<<"Cylinder:";}
friend ostream& operator<<(ostream&,Cylinder&);
};
#endif
test.cpp
#include"test.h"
Point::Point(float a,float b)
{
x=a;
y=b;
}
void Point::setPoint(float a,float b)
{
x=a;
y=b;
}
ostream& operator<<(ostream& output,const Point& p)
{
output<<"["<<p.x<<","<<p.y<<"]";
return output;
}
Circle::Circle(float a,float b,float c):Point(a,b),radius(c)
{
}
void Circle::setRadius(float r)
{
radius=r;
}
float Circle::getRaidus() const
{
return radius;
}
float Circle::area() const
{
return 3.14*radius*radius;
}
ostream& operator<<(ostream& output,const Circle& c)
{
output<<"["<<c.x<<","<<c.y<<"],r="<<c.radius;
return output;
}
Cylinder::Cylinder(float a,float b,float r,float h):Circle(a,b,r),height(h){}
void Cylinder::setHight(float h)
{
height=h;
}
float Cylinder::area() const
{
return 2*Circle::area()+2*3.14*radius*radius;
}
float Cylinder::volume() const
{
return Circle::area()*height;
}
ostream& operator<<(ostream& output,Cylinder& cy)
{
output<<"["<<cy.x<<","<<cy.y<<"],r="<<cy.radius<<","<<cy.height;
return output;
}
main.cpp
#include"test.h"
int main()
{
Point point(3.2,4.5);
Circle circle(2.4,1.2,5.6);
Cylinder cylinder(3.5,6.4,5.2,10.5);
point.shapeName();
std::cout<<point<<std::endl;
circle.shapeName();
std::cout<<circle<<std::endl;
cylinder.shapeName();
std::cout<<cylinder<<std::endl;
Shape *pt;
pt=&point;
pt->shapeName();
pt=&circle;
pt->shapeName();
pt=&cylinder;
pt->shapeName();
return 0;
}
主函数中先后用静态关联和动态关联输出结果。
分别定义Point类对象point,Cirlce 类对象circle,Cylinder类对象cyliner。分别通过对象名去调用shapeName(),这属于静态关联,在编译阶段可以确定应该调用哪个类的shapeName().
定义一个指向基类Shape对象的指针变量pt,使其先后指向3个派生对象,然后通过指针调用shapeName(),这是通过动态关联分别确定应该调用哪个类的shapeName().