我试图在不同的类中声明和调用函数指针,但是编译时会出错。请参考下面的代码。注意:这不是实际的代码,而是修改了变量和函数名称的实际代码的一部分。
文件A.h
typedef bool (A::*add_ptr_Typ)(int a,int b );
class A
{
public:
bool add_func(int a,int b );
void m_assign();
add_ptr_Typ add_ptr;
}文件A.cpp
void A::m_assign()
{
add_ptr = & A::add_func;
}
bool A::add_func(int a,int b )
{
if ((a+b) > 10)
return true;
else
return false;
}文件B.h
class B
{
public:
add_ptr_Typ m_add_ptr;
bool m_process(A* A_ptr);
}文件B.cpp
bool B::m_process(A* A_ptr)
{
m_add_ptr = A_ptr->add_ptr;
(m_add_ptr)(2,3); //error:must use â.*â or â->*â to call pointer-to-member function
(*m_add_ptr)(2,3);//error: invalid use of âunary *â on pointer to member
(this->m_add_ptr)(2,3);//error: must use â.*â or â->*â to call pointer-to-member function
this->m_add_ptr(2,3);//error: pointer to member type bool (A::)(int,int) incompatible with object type B
}我试着用我所知道的所有可能的方式调用函数指针(我不知道其中的一些或全部是错误的)。我在编译过程中得到的错误消息已作为注释放在该行前面。
发布于 2013-11-18 09:03:36
您不是在处理函数指针,而是处理指针到成员函数。这是非常不同的野兽。将后者看作是“对象内函数的标识符”。您必须将它与对象一起使用以获得可调用的内容。换言之,这是:
bool B::m_process(A* A_ptr)
{
m_add_ptr = A_ptr->add_ptr;
(A_ptr->*m_add_ptr)(2, 3);
}->* (和相应的.*)是取消引用指针到成员的操作符.
https://stackoverflow.com/questions/20043676
复制相似问题