//例
class A
{
public:
int func(int x) const;
int example();
};
int A::example()
{
int (*p)(int x);
p = func; //error does not match
return 0;
}
//请问该如何定义一个p才能指向func呢?
发信人: dp2 (死生契阔 与子成说), 信区: CPlusPlus
标 题: Re: 如何定义一个可指向类的非static但是const的函数的函数指针
发信站: 水木社区 (Sun Aug 9 19:43:01 2009), 站内
#include <iostream>
using namespace std;
class A
{
public:
int func(int x) const
{
cout << x << endl;
return 0;
}
int example();
};
int A::example()
{
int (A::*p)(int x) const;
p = &A::func; //error does not match
A* another = new A;
(another->*p)(0);
return 0;
}
int main()
{
A a;
a.example();
return 0;
}
逻辑推理就可以知道需要
考虑非const的情况
int (*p)(int x);
如果不加A::,编译器怎么会知道你是想声明什么?
实际上,A::并不是使用A中的一个名称,而是和后面的*连起来用的,表明是A的一个成员指针