使用using声明成员函数指针别名后调用报错C2064的求助
解决成员函数指针调用的C2064错误
核心问题分析
你遇到的error C2064是因为成员函数指针的调用语法错误。成员函数必须依赖类的实例(this指针)才能调用,直接用stateFuncTable[m_state](nextStateInput)的写法不符合C++语法,编译器无法识别这是类成员函数的调用。
修正步骤
1. 成员函数指针的正确调用方式
将出错行的代码修改为:
m_state = (this->*stateFuncTable[m_state])(nextStateInput);
这里的(this->*func_ptr)是C++中调用成员函数指针的标准语法,必须通过this指针绑定当前对象实例。
2. 修正输入验证逻辑的bug
原代码中的while循环逻辑错误:无论输入是否合法,都会输出错误提示且无限循环。需要调整为只有输入不合法时才提示,并在输入合法时跳出循环:
while (true) { std::cout << "Please input the state you want to transition to next: "; std::cin >> nextStateInput; bool isValid = false; for (int i = 0; i < sizeof inputArray / sizeof inputArray[0]; ++i) { if (nextStateInput == inputArray[i]) { isValid = true; break; } } if (isValid) { break; // 输入合法,跳出循环 } std::cout << "Please enter one of the letters a-e." << std::endl; }
3. 成员函数指针数组初始化的规范写法
虽然原代码的初始化能编译,但加上类作用域和取地址符会更清晰,避免歧义:
StateFunc stateFuncTable[STATE_NUM] = { &Person::IsInStateA, &Person::IsInStateB, &Person::IsInStateC, &Person::IsInStateD, &Person::IsInStateE };
修正后的完整Person.cpp代码
#include <iostream> #include "Person.h" Person::Person() :m_state(A) { } Person::~Person() { } void Person::UpdateState() { char inputArray[] = { 'a','b','c','d','e' }; char nextStateInput; while (true) { std::cout << "Please input the state you want to transition to next: "; std::cin >> nextStateInput; bool isValid = false; for (int i = 0; i < sizeof inputArray / sizeof inputArray[0]; ++i) { if (nextStateInput == inputArray[i]) { isValid = true; break; } } if (isValid) { break; } std::cout << "Please enter one of the letters a-e." << std::endl; } using StateFunc = STATE(Person::*)(char); StateFunc stateFuncTable[STATE_NUM] = { &Person::IsInStateA, &Person::IsInStateB, &Person::IsInStateC, &Person::IsInStateD, &Person::IsInStateE }; // 调用当前状态对应的成员函数,完成状态转换 m_state = (this->*stateFuncTable[m_state])(nextStateInput); } // 以下成员函数实现保持不变 STATE Person::IsInStateA(char nextState) { switch (nextState) { case 'b': return B; case 'd': return D; default: return A; } } STATE Person::IsInStateB(char nextState) { switch (nextState) { case 'c': return C; case 'd': return D; case 'e': return E; default: return B; } } STATE Person::IsInStateC(char nextState) { switch (nextState) { case 'b': return B; default: return C; } } STATE Person::IsInStateD(char nextState) { switch (nextState) { case 'a': return A; case 'e': return E; default: return D; } } STATE Person::IsInStateE(char nextState) { switch (nextState) { case 'a': return A; case 'b': return B; default: return E; } }
额外说明
- 成员函数指针的语法较为特殊,记住必须通过对象实例(这里是
this)来调用,格式为(对象->*函数指针)(参数)或(对象.*函数指针)(参数)。 - 输入验证部分的修正确保程序能正确接收合法输入后再执行状态转换,避免无限循环。
内容的提问来源于stack exchange,提问作者Transwater
相关产品推荐
相关产品推荐

