成员函数指针需通过类实例调用,适用于回调、状态机等动态绑定场景。声明形式为返回类型 (类名::*指针名)(参数),调用时使用.*或->*操作符;静态成员函数指针与普通函数指针兼容,可直接赋值调用;常用于策略模式等需运行时选择方法的轻量级高性能场景。

在C++中,成员函数指针与普通函数指针不同,因为它必须通过类的实例来调用,不能直接像普通函数那样使用。成员函数指针主要用于需要动态绑定类方法的场景,比如回调机制、状态机或事件处理系统。
假设有一个类 MyClass,它包含一个成员函数:
class MyClass {
public:
int getValue(int x) {
return x * 2;
}
};
要声明指向该成员函数的指针,语法如下:
int (MyClass::*ptr)(int) = &MyClass::getValue;
解释:
int (MyClass::*) 表示“指向 MyClass 类中返回 int 且接受 int 参数的成员函数”的指针类型。
ptr 是变量名。
&MyClass::getValue 取成员函数地址。
立即学习“C++免费学习笔记(深入)”;
调用时必须通过对象(或对象指针)进行。有两种方式:
MyClass obj; int result1 = (obj.*ptr)(5); // 使用 .*,result1 = 10 <p>MyClass<em> pObj = &obj; int result2 = (pObj-></em>ptr)(5); // 使用 ->*,result2 = 10</p>
静态成员函数没有 this 指针,因此它的指针与普通函数指针兼容:
class MyClass {
public:
static int staticFunc(int x) {
return x + 1;
}
};
<p>// 可以用普通函数指针
int (*staticPtr)(int) = &MyClass::staticFunc;
int result = staticPtr(5); // result = 6</p>成员函数指针可用于实现简单的策略模式或状态切换:
class Calculator {
public:
double add(double a, double b) { return a + b; }
double sub(double a, double b) { return a - b; }
<pre class='brush:php;toolbar:false;'>using Op = double (Calculator::*)(double, double);
double compute(Op op, double a, double b) {
return (this->*op)(a, b);
}};
// 使用 Calculator calc; double result = calc.compute(&Calculator::add, 2.0, 3.0); // result = 5.0
基本上就这些。成员函数指针语法略显复杂,但理解后可以灵活用于需要运行时选择类方法的场合。注意不要和虚函数或std::function混淆,它们是更高级的多态或泛型替代方案。成员函数指针适合轻量级、高性能的绑定需求。
以上就是c++++中类的成员函数指针如何使用 _c++类成员函数指针使用方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号