我已经设法用这段代码制作了一个“指向成员函数数组”,它工作正常......
typedef string (MyReportHelper::*reportFunctions)();
MyReportHelper helper;
void internalPointersTest(){
reportFunctions reportFunArray[] = {
&MyReportHelper::getVersion,
&MyReportHelper::getModel,
&MyReportHelper::getUsername,
};
int arrSize = sizeof(reportFunArray)/sizeof(reportFunArray[0]);
for(int i = 0; i < arrSize; i++){
string result = (helper.*reportFunArray[i])();
printf("%s", result);
}
}
但是,如果我将数组声明放在我的函数之外,就像下面的代码一样,我会在 Visual Studio 中遇到缓冲区溢出或访问冲突,尽管代码可以编译.
typedef string (MyReportHelper::*reportFunctions)();
MyReportHelper helper;
reportFunctions reportFunArray[] =
{
&MyReportHelper::getVersion,
&MyReportHelper::getModel,
&MyReportHelper::getUsername,
};
void internalPointersTest(){
int arrSize = sizeof(reportFunArray)/sizeof(reportFunArray[0]);
for(int i = 0; i < arrSize; i++)
{
//next line will fail
string result = (helper.*reportFunArray[i])();
printf("%s", result);
}
}
有谁知道如何解释为什么我需要将其保留在函数范围内?