在C++中使用成员函数指针

deltamaster posted @ Dec 12, 2011 11:45:20 AM in 未分类 with tags C++ 指针 函数指针 成员函数 作用域 , 4678 阅读

函数指针的语法相对比较复杂,成员函数指针则在此基础上进一步引入了类作用域限定。让我们来了解一下成员函数指针的写法。

首先回顾一下函数指针的使用方法。有这样一个函数:

 

double func(double x)
{
	return 3.14 * x;
}

我们这样声明函数指针,并且进行调用:

 

	double (*pfunc)(double x);
	pfunc = &func;
	cout << (*pfunc)(1.1) << endl;

指针的声明包括返回类型、指针名和函数的参数表,对于一个强类型的编译型语言,这些要素都必不可少。由于运算符优先级的规定,还要特别注意在适当的位置加上括号。

对于成员函数指针,就是增加了一个作用域限定。

首先有一个类A,包含几个类型相同的函数。

 

class A
{
public:
	void f1(int x)
	{
		cout << "f1:" << x << endl;
	}
	void f2(int x)
	{
		cout << "f2:" << x << endl;
	}
	void f3(int x)
	{
		cout << "f3:" << x << endl;
	}
};

然后类B的对象会调用类A的对象的成员函数,然而具体调用哪一个还不知道,我们通过指针的方式来实现,在运行时将指针指向一个类型兼容的成员函数。

 

class B
{
public:
	void (A::*pf) (int x); //注意作用域运算符和*的次序,括号不能省略

	void callF(int x)
	{
		A a;
		(a.*pf)(x);
	}
};

我们在外部实例化B的对象,然后为B的成员函数指针赋值,确定将要调用的是哪一个函数。

 

	cout << "Hello world!" << endl;
	B b;
	b.pf = &A::f2;
	b.callF(5);
* 本文在CC BY-SA(署名-相同方式共享)协议下发布。
zhjx 说:
Dec 12, 2011 10:38:55 PM

都已经用函数指针了为何不用functor?

zhjx 说:
Dec 12, 2011 10:40:24 PM

@zhjx: 后面的call我没有看见
当我没说罢.........

Emma 说:
Dec 05, 2022 10:24:22 PM

In C++, member function pointers allow you to store the address of a member function in a variable. This can be useful when you want to call a member function from a different part of your code, or from a different object. To use member function pointers, you first need to declare a function pointer variable with the Lab grown diamonds same signature as the member function you want to store. For example, if you have a class called MyClass with a member function called MyFunction, you would declare a function pointer like this: MyClass::MyFunctionPtr MyFunctionPtr; You can then store the address of MyFunction in MyFunctionPtr like this: MyFunctionPtr = &MyClass::MyFunction;

Haryana 8th Model P 说:
Jul 29, 2023 01:18:21 AM

HBSE 6th Class Routine will be Announce in the month of December Students who have Appeared in the 6th Class Examination can Easily Check Their Solved Paper our Web portal Available, Students shall use HBSE Class Sample Paper 2024 Haryana 8th Model Paper 2024 for Mock Tests to Improve their Skills in Annual Exam 2024 Students who have completed their Preparation can Start Practicing the Haryana Board Class Last Year Exam Model Paper 2024. we Suggest the Students Solved Question Paper for Practice Purpose, in fact by Practicing Question Paper Students can get the brief idea about the Public Examination 2024

seo service london 说:
Jan 16, 2024 10:44:09 PM

Very good blog post.Much thanks again. Cool


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter