企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 概述 虚函数或纯虚函数自身并不实现任何功能,各个不同的类在继承时才实现不同的功能,因此,同一个虚函数在执行时具有了多种不同功能,称之为“多态”。 ## 求面积 <details> <summary>main.cpp</summary> ``` #include <iostream> #include <string> using namespace std; class area { public: double dim1, dim2; void setData(double d1, double d2) { dim1 = d1; dim2 = d2; } void getData(double &d1, double &d2) { d1 = dim1; d2 = dim2; } virtual double getArea() = 0; }; class rectangle : public area { public: double getArea() { return dim1*dim2; } }; class triangle : public area { public: double getArea() { return dim1*dim2/2; } }; int main() { area *p; rectangle r; r.setData(2.0,3.0); cout << "r.getArea() : "<< r.getArea() <<endl; triangle t; t.setData(2.0,3.0); cout << "t.getArea() : "<< t.getArea() <<endl; p = &r; cout << "p->getArea() : " << p->getArea() <<endl; p = &t; cout << "p->getArea() : " << p->getArea() <<endl; return 0; } ``` </details> <br/> 输出 ``` r.getArea() : 6 t.getArea() : 3 p->getArea() : 6 p->getArea() : 3 ``` ## 队列和堆栈