您当前位置:资讯中心 >开发 >浏览文章

探秘C++虚函数:多态的奇妙世界

来源:不详 日期:2024/1/23 10:13:57 阅读量:(0)

虚函数是C++面向对象编程中的精髓之一,它为我们提供了多态性的魔法钥匙。

1. 虚函数的含义与作用

在C++中,虚函数是一种允许在派生类中重新定义的函数。其背后的核心思想是多态性,通过在基类中声明虚函数,我们可以以一种统一的方式处理不同类型的对象。让我们先来看一个简单的例子:


#include <iostream>
using namespace std;
class Shape {
public:
    virtual void draw() {
        cout << "Drawing a shape" << endl;
    }
};
class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing a circle" << endl;
    }
};
class Square : public Shape {
public:
    void draw() override {
        cout << "Drawing a square" << endl;
    }
};

int main() {
    Circle circle;
    Square square;
    // 使用基类指针调用虚函数,实现多态
    Shape* shape1 = &circle;
    Shape* shape2 = &square
    shape1->draw(); // 输出 "Drawing a circle"
    shape2->draw(); // 输出 "Drawing a square"
    return 0;
}
关键字:
声明:我公司网站部分信息和资讯来自于网络,若涉及版权相关问题请致电(63937922)或在线提交留言告知,我们会第一时间屏蔽删除。
有价值
0% (0)
无价值
0% (10)

分享转发:

发表评论请先登录后发表评论。愿您的每句评论,都能给大家的生活添色彩,带来共鸣,带来思索,带来快乐。