#include <iostream>
using namespace std;
//多态
//父类(基类)Shape
class Shape {
protected:
int width, height;
public:
Shape(int a = 0, int b = 0)
{
width = a;
height = b;
}
//虚函数 :在基类中使用关键字virtal声明的函数,在派生类中重新定义 基类 中定义的虚函数时,
//会告诉编译器不要静态链接到该函数
virtual int area()
{
cout << "parent class area :" << endl;
return 0;
}
//纯虚函数(这种写法也可以)
/*
virtual int area() = 0; //告诉编译器,函数没有主体,上面的虚函数是纯虚函数
*/
};
//子类 Rectangle
class Rectangle :public Shape {
public:
Rectangle(int a = 0, int b = 0) :Shape(a, b) {}
//对基类虚函数area()的重载
int area()
{
cout << "Rectangle class area :" << endl;
return (width * height);
}
};
//子类 Triangle
class Triangle :public Shape {
public:
Triangle( int a=0,int b=0):Shape(a,b){ }
int area()
{
cout << "Triangle class area :" << endl;
return (w
c++ 多态&虚函数&纯虚函数
最新推荐文章于 2023-02-17 00:06:15 发布