这段程序,在DEV-C++中也提示出错


#include <iostream>
using namespace std;
class Test
{
    int x,y;
    public:
        Test(int i,int j=0)
        {x=i;y=j;}
        int get(int i ,int j)
        {return i+j;}
        
};

int main()
{
    Test t1(2),t2(4,6);
    int (Test::*p)(int ,int=10);  //看不懂
    p=Test::get;
    cout<<(t1.*p)(5)<<endl;  //看不懂
    Test *p1=&t2;
    cout<<(p1->*p)(7,20)<<endl; //看不懂
    return 0;
    
}

}

看不懂的是函数指针申明和调用
修改如下:

int main()
{
    Test t1(2),t2(4,6);
    typedef int (Test::*p)(int, int);
    p fun =&Test::get;
    cout<<(t1.*fun)(5,1)<<endl;  //看不懂
    Test *p1=&t2;
    cout<<(p1->*fun)(7,20)<<endl; //看不懂
    return 0;
    
}

int (Test::*p)(int ,int=10);  //这里声明一个函数,这个函数是Test类的一个成员函数,这个函数有两个int类型的参数,并且,第二个参数的默认值是10,p是函数指针
    p=Test::get;  //这里让p指向Test类的get函数
    cout<<(t1.*p)(5)<<endl;  //因为上面一句让p指向Test类的get函数,所以这里(t1.*p)(5)就相当于t1.get(5,10),10是p的默认参数