您的位置:首页 > 其它

函数指针

2016-02-16 00:08 232 查看

(1/2)类型

普通函数指针不能被赋值为成员函数的地址。

int (*pFunc)();

pFunc是一个函数指针,而int (*)()是类型。

成员函数地址要赋值给成员函数指针。

class Base
{
public:
int func() { return 1; }
};

int main()
{
int (*pFunc)();
pFunc = &Base::func;  //error: cannot convert 'int (Base::*)()' to 'int (*)()' in assignment
return 0;
}


class Base
{
public:
int func() { return 1; }
};

int main()
{
int (Base::*pFunc)(); // OK
pFunc = &Base::func;
return 0;
}


再来:

class Base
{
public:
int func() { return 1; }
};
class Derived : public Base
{
public:
int foo() { return 1; }
};

int main()
{
typedef int (Base::*FuncPtr)();
FuncPtr fPtr = &Derived::foo; // error
return 0;
}


需进行强制类型转换

......

FuncPtr fPtr = (FuncPtr)&Derived::foo;  // OK


反过来,基类成员函数地址可赋值给指向派生类成员函数的指针。

class Base
{
public:
int func() { return 1; }
};
class Derived : public Base
{
public:
int foo() { return 1; }
};

int main()
{
typedef int (Derived::*FuncPtr)();
FuncPtr fPtr = &Base::func;  // OK
return 0;
}


(2/2)调用

class Base
{
public:
virtual void func(int i) { cout << "Base: " << i << endl; }
};
class Derived : public Base
{
public:
virtual void func(int i) { cout << "Derived: " << i << endl; }
};

int main()
{
typedef void (Base::*FuncPtr)(int);
FuncPtr fPtr = &Base::func;
Base b;
(b.*fPtr)(2);
Derived* dPtr = new Derived();
(dPtr->*fPtr)(2);
Base* bPtr = new Derived();
(bPtr->*fPtr)(2);
return 0;
}


output:

Base: 2
Derived: 2
Derived: 2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: