C++这个表达式是什么意思啊?

来源:百度知道 编辑:UC知道 时间:2024/06/01 12:03:54
int (Sample::*fp) ();
这个表达式在主函数中,其中Sample是类名,Sample类里有两个int成员函数,不过好像跟这个没关系......
如果是成员函数指针int(Sample::*fp)这样写不就行了,还加括号干什么啊?

成员函数指针,如:

#include <iostream>
using namespace std;

class A
{
public:
A(int _n) : n(_n){}
int square(){return n * n;}
int cube(){return n *= n * n;}

private:
int n;
};

int main()
{
A a(5), *pa = &a;

int (A::*pm)() = &A::square;
cout << "square: " << (a.*pm)() << '\n';

pm = &A::cube;
cout << "cube : " << (pa->*pm)() << '\n';
}

补充:你试试把上面的例子改成int (A::*pm) = &A::square编译器会让你通过么?这样你只是定义了一个指向int类型的指针而不是指向一个返回int值不接受参数的函数的指针。

函数指针你看了没,建议你去复习下...