您的位置:首页 > 其它

定义一个可指向类的非static但是const的函数的函数指针

2009-08-09 21:52 239 查看
//例
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的一个成员指针
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐