溫馨提示×

如何在c++中實現base類的多態

c++
小樊
85
2024-09-04 18:37:55
欄目: 編程語言

在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()函數是虛函數,因此會根據派生類的實現進行調用,實現了多態性。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女