首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请教class成员函数指针如何用?

2013-03-14 
请问class成员函数指针怎么用??本帖最后由 weiwuyuan 于 2013-03-10 15:30:42 编辑class CTest{public:CTe

请问class成员函数指针怎么用??
本帖最后由 weiwuyuan 于 2013-03-10 15:30:42 编辑


class CTest
{
public:
CTest()
{
CommandFunc p = NULL;
p = Test;

p(10);
}

typedef int (CTest::*CommandFunc)(int a);

int Test(int a)
{
return a;
}
};


C函数是可以这样写的,可是class成员函数不能这么写么?
编译提示:CTest::Test”: 函数调用缺少参数列表;请使用“&CTest::Test”创建指向成员的指针
[解决办法]
expression .* expression
expression –>* expression


#include <iostream>

using namespace std;

class Testpm {
public:
   void m_func1() { cout << "m_func1\n"; }
   int m_num;
};

// Define derived types pmfn and pmd.
// These types are pointers to members m_func1() and
// m_num, respectively.
void (Testpm::*pmfn)() = &Testpm::m_func1;
int Testpm::*pmd = &Testpm::m_num;

int main() {
   Testpm ATestpm;
   Testpm *pTestpm = new Testpm;

// Access the member function
   (ATestpm.*pmfn)();
   (pTestpm->*pmfn)();   // Parentheses required since * binds
                        // less tightly than the function call.

// Access the member data
   ATestpm.*pmd = 1;
   pTestpm->*pmd = 2;

   cout  << ATestpm.*pmd << endl
         << pTestpm->*pmd << endl;
   delete pTestpm;
}

热点排行