C++ 多态 虚函数virtual
先解释虚函数,对于基类,子类继承基类后可能会调用其某个函数FA,而不同的子类继承了同一个基类后需要基类内某个同样的函数FA但又不是同个作用,此时则会在对应的子类内对应重载派生出FA_B函数和FA_C函数,而这时要求FA为虚函数(virtual)
那为什么不各自写成一个函数B和C呢?这就是多态的意义
对于基类A和子类B,C有
B b; C c; A *ab = &b; A *ac = &c;
则基类指针指向子类,此时调用其内函数
ab->FA;
ac->FA;
虽然是同一个类的同一个函数,但是其效果不一致,这就是多态,即规范了写法又实现灵活的功能。
用法:
基类内虚函数前缀virtual,纯虚函数则以const=0结尾,必须重载功能才有具体意义,否则无法实例化,这就是抽象类;而非纯虚函数则是先定义好功能,子类可选择性进行重载。
纯虚函数例子
#include <iostream> // 形状的基类 class Shape { public: virtual double calculateArea() const = 0; }; // 矩形类 class Rectangle : public Shape { private: double length; double width; public: Rectangle(double l, double w) : length(l), width(w) {} double calculateArea() const override { return length * width; } }; // 圆类 class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double calculateArea() const override { return 3.14 * radius * radius; } }; int main() { Rectangle rectangle(5, 4); Circle circle(3); Shape* shape1 = &rectangle; Shape* shape2 = &circle; // 通过基类指针调用不同对象的函数 std::cout << "Area of rectangle: " << shape1->calculateArea() << std::endl; std::cout << "Area of circle: " << shape2->calculateArea() << std::endl; return 0; }
非纯虚函数例子
#include <iostream> // 形状的基类 class Shape { public: virtual double calculateArea() { std::cout << "here!" << std::endl; return 0; }; }; // 矩形类 class Rectangle : public Shape { private: double length; double width; public: Rectangle(double l, double w) : length(l), width(w) {} double calculateArea() { return length * width; } }; // 圆类 class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double calculateArea() { return 3.14 * radius * radius; } }; int main() { Rectangle rectangle(5, 4); Circle circle(3); Shape* shape1 = &rectangle; Shape* shape2 = &circle; // 通过基类指针调用不同对象的函数 std::cout << "Area of rectangle: " << shape1->calculateArea() << std::endl; std::cout << "Area of circle: " << shape2->calculateArea() << std::endl; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通