本篇介绍C++类的多态性,当类之间存在继承关系时,调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。
/*
* Author:W;
* 类的多态:virtual虚函数:调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。
*/
//引入头文件:头文件包含了程序中必需的或有用的信息
#include <iostream>
using namespace std;
/*基类:形状*/
class Shape
{
public:
//构造函数
Shape(float wid, float hei)
{
width = wid;
height = hei;
}
//虚函数
//virtual float getArea(){}
//(纯)虚函数:计算形状面积
virtual float getArea() = 0;
protected:
float width;
float height;
};
/*正方形*/
class Rectangle : public Shape
{
public:
Rectangle(float wid, float hei) :Shape(wid, hei) {}
//覆写面积计算
float getArea()
{
cout << "正方形的面积 S = " << width * height << endl;
return width * height;
}
};
/*三角形*/
class Triangle : public Shape
{
public:
Triangle(float wid, float hei) :Shape(wid, hei) {}
//覆写面积计算
float getArea()
{
cout << "三角形的面积 S = " << (width * height) / 2 << endl;
return (width * height)/2;
}
};
//main程序执行入口函数
int main()
{
Shape* shape = NULL;
Triangle triangle(3,5);
Rectangle rectAngle(4, 7);
//指向三角形对象地址
shape = ▵
shape->getArea();
//指向正方形对象地址
shape = &rectAngle;
shape->getArea();
}
运行结果如下: