5.2向上类型转换
根据赋值兼容原则,可以使用派生类的对象代替基类对象。向上类型转换就是把一个派生类的对象作为基类的对象来使用。
下面通过一个程序来加深对它的理解
#include <iostream>
using namespace std;
class Point
{public:
Point(double a = 0, double b = 0) { x = a; y = b; }
double Area( )
{ cout << "Call Point’s Area function." << endl;
return 0.0;
}
protected:
double x, y; // 点的坐标值
};
class Rectangle: public Point
{public:
Rectangle(double a = 0, double b = 0, double c = 0, double d = 0): Point(a, b)
{ x1 = c; y1 = d; }
double Area( )
{
cout << "Call Rectangle’s Area function." << endl;
return (x - x1)*(y - y1);
}
protected:
double x1, y1;//长方形右下角点的坐标值,基类中x, y为左上角坐标点的值
};
class Circle: public Point
{public:
Circle(double a = 0, double b = 0, double c = 0): Point(a, b){ r = c; }
double Area( )
{
cout << "Call Circle’s Area function." << endl;
return 3.14*r*r;
}
protected:
double r; //圆半径,基类中x, y为圆心坐标点的坐标值
};
double CalcArea(Point &ref){ return ( ref. Area( ) ); }
int main( )
{
Point p(0, 0);
Rectangle r(0, 0, 1, 1);
Circle c(0, 0, 1);
cout << CalcArea(p) << endl;
cout << CalcArea(r) << endl;
cout << CalcArea(c) << endl;
return 0;
}
从运行结果来看,3调用的都是point::area(),这不是我们想要的结果。为了实现灵活的调用,我们需要知道“绑定”这个概念。