溫馨提示×

C++函數對象怎樣進行多態處理

c++
小樊
93
2024-10-30 16:20:26
欄目: 編程語言

在C++中,函數對象(也稱為仿函數或functor)可以通過使用虛函數實現多態處理。虛函數是在基類中聲明的,可以在派生類中重寫。當使用基類指針或引用調用虛函數時,會根據對象的實際類型調用相應的重寫版本。這里是一個簡單的示例:

#include <iostream>

// 基類:函數對象
class FunctionObject {
public:
    // 虛函數,用于多態處理
    virtual int execute(int a, int b) {
        return a + b;
    }
};

// 派生類1:重寫execute函數
class DerivedFunctionObject1 : public FunctionObject {
public:
    int execute(int a, int b) override {
        return a * b;
    }
};

// 派生類2:重寫execute函數
class DerivedFunctionObject2 : public FunctionObject {
public:
    int execute(int a, int b) override {
        return a - b;
    }
};

int main() {
    // 使用基類指針指向派生類對象
    FunctionObject* functionObject1 = new DerivedFunctionObject1();
    FunctionObject* functionObject2 = new DerivedFunctionObject2();

    // 調用多態函數
    std::cout << "Result of functionObject1: " << functionObject1->execute(3, 4) << std::endl;
    std::cout << "Result of functionObject2: " << functionObject2->execute(3, 4) << std::endl;

    // 釋放內存
    delete functionObject1;
    delete functionObject2;

    return 0;
}

在這個示例中,我們定義了一個基類FunctionObject,其中包含一個虛函數execute。然后我們創建了兩個派生類DerivedFunctionObject1DerivedFunctionObject2,它們分別重寫了execute函數。在main函數中,我們使用基類指針指向派生類對象,并通過基類指針調用多態函數。輸出結果將根據對象的實際類型調用相應的重寫版本。

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