如何在c++中实现base类的多态

   2024-09-30 6730
核心提示:在C++中,实现基类(Base Class)的多态性可以通过虚函数(Virtual Functions)和纯虚函数(Pure Virtual Functions)来完成。多

在C++中,实现基类(Base Class)的多态性可以通过虚函数(Virtual Functions)和纯虚函数(Pure Virtual Functions)来完成。多态是面向对象编程的一个重要特性,它允许我们使用基类类型的指针或引用来操作派生类对象。

以下是一个关于如何在C++中实现基类的多态性的示例:

#include<iostream>// 基类(Base Class)class Shape {public:    // 虚函数(Virtual Function)    virtual void draw() {        std::cout << "Drawing a shape"<< std::endl;    }};// 派生类(Derived Class)class Circle : public Shape {public:    void draw() override {        std::cout << "Drawing a circle"<< std::endl;    }};// 派生类(Derived Class)class Rectangle : public Shape {public:    void draw() override {        std::cout << "Drawing a rectangle"<< std::endl;    }};int main() {    Shape* shape1 = new Circle();    Shape* shape2 = new Rectangle();    shape1->draw(); // 输出 "Drawing a circle"    shape2->draw(); // 输出 "Drawing a rectangle"    delete shape1;    delete shape2;    return 0;}

在这个示例中,我们定义了一个基类Shape,其中包含一个虚函数draw()。然后,我们创建了两个派生类CircleRectangle,它们分别重写了draw()函数。在main()函数中,我们使用基类指针分别指向派生类对象,并调用draw()函数。由于draw()函数是虚函数,因此会根据派生类的实现进行调用,实现了多态性。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号