gpt4 book ai didi

c++ - 指向不同类函数的函数指针数组

转载 作者:行者123 更新时间:2023-11-28 02:15:52 25 4
gpt4 key购买 nike

我有一个 MyClass 类。在其中,我想创建一个函数指针数组,并用另一个类 (MemberClass) 的函数初始化该数组。MyClass 有一个指向 MemberClass 作为成员的指针。但是我得到了这个编译时错误错误 C2440:“正在初始化”:无法从“void (__thiscall MyMemberClass::* )(void)”转换为“F”

//This class has the function that I want to create a function pointer to
class MemberClass
{

private:

int myValue1;
int myValue2;

public:

int GetValue1() //I want to point to this function from a function pointer in another class
{

return myvalue1;
}

int GetValue2() //I want to point to this function from a function pointer in another class
{

return myvalue2;
}


}




//This has array of function pointer that I want to point to member function of another class

Class MyClass
{

typedef void(*F)();


private:
MemberClass* mclass;
F[] f;
Process();
}

.cpp

MyClass::MyClass()
{
f[2] = {&MemberClass::GetValue1, &MemberClass::GetValue2} //This line throws error

//error C2440: 'initializing' : cannot convert from 'void (__thiscall MyMemberClass::* )(void)' to 'F'

}

void MyClass::Processing()
{

//This is how I am hoping to use the function pointer array
F[Index]();

}

最佳答案

F 被声明为指向函数的指针,没有参数返回 void。但是您的函数返回 int,并且是 MemberClass 的成员函数,而不是普通函数。所以你需要的类型是

typedef int (MemberClass::*F)();

调用它也比较有趣:

int result = (mclass->*f[index])();

关于c++ - 指向不同类函数的函数指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34053089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com