首页 > 文章列表 > C++ 函数指针如何用于对象方法?

C++ 函数指针如何用于对象方法?

212 2025-01-29

在 C++ 中,通过函数指针可以将对象的方法视为常规函数,它的具体操作步骤如下:将对象方法转换为函数指针:使用 std::mem_fun 函数模板,如:auto function_pointer = std::mem_fun(&Object::Method);调用函数指针:使用语法 function_pointer(object),其中 object 是调用方法的对象。

C++ 函数指针如何用于对象方法?

C++ 函数指针如何用于对象方法?

在 C++ 中,通过函数指针可以将对象的方法视为常规函数。这在需要动态调用方法或向库添加方法时特别有用。

将对象方法转换为函数指针

要将对象方法转换为函数指针,请使用 std::mem_fun 函数模板:

auto function_pointer = std::mem_fun(&Object::Method);

此处,Object 是对象类型,Method 是要转换的方法的名称。

函数指针调用

要调用通过函数指针转换的方法,请使用以下语法:

function_pointer(object);

此处,object 是调用方法的对象。

实战案例

以下是一个使用函数指针排序对象的案例:

#include <iostream>
#include <vector>
#include <algorithm>

class Person {
public:
    std::string name;
    int age;

    bool operator<(const Person& other) const {
        return age < other.age;
    }
};

int main() {
    std::vector<Person> people = {
        {"John", 30},
        {"Mary", 25},
        {"Bob", 40},
    };

    // 使用函数指针排序
    auto sort_by_age = std::mem_fun(&Person::operator<);
    std::sort(people.begin(), people.end(), sort_by_age);

    // 打印排序后的结果
    for (const auto& person : people) {
        std::cout << person.name << ", " << person.age << std::endl;
    }

    return 0;
}

输出:

Mary, 25
John, 30
Bob, 40