指向成员功能的功能指针
Function pointer pointing to member function
我很难创建一个普通的旧功能指针,并将其分配给 myClass 对象 obj 的成员函数。我在下面复制了一个样本,
class myclass
{
public:
myclass() { i = 38; }
int i;
void func() { cout << "inside func" << endl; }
};
int main()
{
myclass obj;
myclass *objptr = &obj;
int myclass::*iptr1; //decl pointer to member
iptr1 = &myclass::i; //obtain offset
cout << obj.*iptr1 << endl; //dereference using object; use .*
cout << objptr->*iptr1 << endl; //dereference using pointer to object; use ->*
int *iptr2; //decl plain old integer pointer
iptr2 = &obj.i; //obtain address of member
cout << *iptr2 << endl; //dereference
void(myclass::*fptr1)(); //decl pointer to member
fptr1 = &myclass::func; //obatain offset
(obj.*fptr1)(); //dereference using object; use .*
(objptr->*fptr1)(); //dereference using pointer to object; use ->*
/*void(*fptr2) (); // decl plain old function pointer
fptr2 = obj.func; //this is the exact line that doesn't compile
(*fptr2) ();*/ //after having a pointer to the member function *func* I would like to call it like this, if possible, from this plain old pointer
getchar();
return 0;
}
我会出现以下错误,如果三行不被选中
Error C3867 'myclass::func': non-standard syntax; use '&' to create a
pointer to member
Error C2440 '=': cannot convert from 'void (__thiscall myclass::* )
(void)' to 'void (__cdecl *)(void)'
如果不是三行,我得到了预期的输出
38
38
38
inside func
inside func
我需要使用普通的旧功能指针而不是类成员功能的指针来获取Func 内部的第三个。需要一些帮助。我在这里缺少语法吗?!
func
是一个非静态成员函数。它需要一个 myclass
对象才能在功能上操作(函数内的this
然后指向(。好像该函数具有无形的myclass
参数。
fptr2
是一个函数的函数指针,无需任何参数,因此拒绝了分配。这是一些替代解决方案:
- 使
func
静态。 - 将
fptr2
的类型更改为指针到会员。 - 请勿使用原始功能指针;切换到C 11 lambdas和/或
std::function
。
这是后者的一个示例:
std::function<void()> f2;
f2 = [&]{ obj.func(); };
f2();
相关文章:
- 如何定义和设置指向模板类方法的功能指针
- 将状态传递给功能指针
- 如何使用结构内的功能指针调用私有函数
- 功能指针不起作用(C )
- 将C 方法作为功能指针传递
- 优化调用一系列功能指针
- C 功能指针和成员功能指针
- 当直接分配时,为什么此功能指针分配起作用,而不是与有条件的操作员一起使用
- 功能指针的静态初始化
- 功能指针参数参数转换为const
- 使用lambda在功能指针铸造时双免费
- 如何在两个类之间使用功能指针
- exc_bad_access on for loop(数组功能指针)
- 如何通过功能指针调用派生方法
- 虚拟功能指针指向派生类中的函数
- C :铸造成员功能指针
- 指向成员功能的功能指针
- 正确施放以指向返回功能的函数的功能指针
- 当用作模板参数时,功能指针是否需要指向具有外部链接的函数
- 在堆中创建功能指针的数组