溫馨提示×

C++虛擬函數怎么應用

c++
小億
94
2024-03-28 17:26:04
欄目: 云計算

C++中的虛擬函數是通過在基類中聲明為虛擬函數來實現多態性的特性。在派生類中重寫這些虛擬函數,可以根據實際對象的類型來調用相應的函數。以下是一個簡單的示例:

#include <iostream>

class Shape {
public:
    virtual void draw() {
        std::cout << "Drawing a shape" << std::endl;
    }
};

class Circle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a circle" << std::endl;
    }
};

class Square : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a square" << std::endl;
    }
};

int main() {
    Shape* shape1 = new Circle();
    Shape* shape2 = new Square();

    shape1->draw(); // 輸出 "Drawing a circle"
    shape2->draw(); // 輸出 "Drawing a square"

    delete shape1;
    delete shape2;

    return 0;
}

在上面的示例中,我們定義了一個基類 Shape,并在其中聲明了一個虛擬函數 draw()。然后定義了兩個派生類 CircleSquare,分別重寫了 draw() 函數。在 main 函數中,我們創建了一個指向 CircleSquare 對象的 Shape 指針,并分別調用它們的 draw() 函數,根據實際對象的類型輸出不同的結果。

通過使用虛擬函數和多態性,可以實現基于對象實際類型的函數調用,從而實現更加靈活和可擴展的代碼結構。

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