我的示例和评论已经足够详细了,这里是:
class C
{
public:
void (*m_ffp)(); //free-function pointer (C member)
void (C::*m_mfp)(); //C::member-function pointer (C member)
void doSomething() //from within the class:
{
m_ffp(); //call the free function pointer
(this->*m_mfp)(); //call the member-function pointer
}
};
void (C::*g_mfp)(); //C::member-function pointer ('external', not a C-member)
int main()
{
C c;
//from outside the class:
c.m_ffp(); //call the C-owned function pointer directly
(c.*g_mfp)(); //call the non-member C::member-function pointer (external one)
(c.*m_mfp)(); // error C2065 'm_mfp': undeclared identifier
//how to call the C-member member-function pointer directly from outside the class?
}
因此,记录一下 - “直接”调用对象的公共(public)成员指针到成员函数的语法是什么(当然是从类外部/由用户)?
顺便说一句。这与验证/分配这些指针的任何函数无关(我在真实的程序中执行此操作),请帮助我对其进行编译。最佳答案
由于m_mfp
是C
类型的成员,因此需要使用.
运算符来获取该成员:
(c.*m_mfp)(); // error C2065 'm_mfp': undeclared identifier
^ should be c.m_mfp
所以正确的调用如下所示:
(c.*c.m_mfp)();
此外,在 C++17 及更高版本中,您可以使用 std::invoke
摆脱丑陋的指向成员的指针语法:
std::invoke(c.m_mfp, c);
关于c++ - 如何通过本身是类成员的指针调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701062/