为什么我不能分配一个函数指针变量来指向特定的函数。错误如下
Why cannot I assign a function pointer variable to point to a specific function. Error is below
我有以下错误
"Assigning to 'TreeLeaf(TreeLeaf::*)(TreeLeaf,TreeLeaf)' from incompatibale type 'TreeLeaf(TreeLeaf,TreeLeaf)'"
在我的 TreeLeaf.h 中,我有以下代码
class TreeLeaf
{
public:
void checkVaribleValue(string command);
int number;
bool isOperator = false;
TreeLeaf (TreeLeaf::*operation)(TreeLeaf var1, TreeLeaf var2);
static TreeLeaf add(TreeLeaf var1, TreeLeaf var2);
};
在我的 TreeLeaf.cpp 中,我有以下代码
#include "TreeLeaf.h"
void TreeLeaf::checkVaribleValue(string command)
{
if(isdigit(command[0]) || (command[0] == '-' && isdigit(command[1])))
{
number = stoi(command);
}
else
{
switch(command[0])
{
case '+':
isOperator = true;// will used to know that that it operates on other leafs.
operation = add;
break;
}
}
}
TreeLeaf TreeLeaf::add(TreeLeaf var1, TreeLeaf var2)
{
//TODO check type for now just working with ints
TreeLeaf result;
result.number = var1.number + var2.number;
return result;
}
当我尝试将操作分配给 add(operation = add;
) 时出现错误。
我正在使用 XCode 7.3.
静态成员函数与成员函数不同。成员函数需要一个 class 的实例,而静态成员函数不需要,因此静态成员函数就像一个全局函数,但它的名称范围为 class。如果你想存储指向 add
的指针,那么你将拥有
TreeLeaf (*operation)(TreeLeaf,TreeLeaf);
然后
operation = add;
会是
operation = &TreeLeaf::add;
我有以下错误
"Assigning to 'TreeLeaf(TreeLeaf::*)(TreeLeaf,TreeLeaf)' from incompatibale type 'TreeLeaf(TreeLeaf,TreeLeaf)'"
在我的 TreeLeaf.h 中,我有以下代码
class TreeLeaf
{
public:
void checkVaribleValue(string command);
int number;
bool isOperator = false;
TreeLeaf (TreeLeaf::*operation)(TreeLeaf var1, TreeLeaf var2);
static TreeLeaf add(TreeLeaf var1, TreeLeaf var2);
};
在我的 TreeLeaf.cpp 中,我有以下代码
#include "TreeLeaf.h"
void TreeLeaf::checkVaribleValue(string command)
{
if(isdigit(command[0]) || (command[0] == '-' && isdigit(command[1])))
{
number = stoi(command);
}
else
{
switch(command[0])
{
case '+':
isOperator = true;// will used to know that that it operates on other leafs.
operation = add;
break;
}
}
}
TreeLeaf TreeLeaf::add(TreeLeaf var1, TreeLeaf var2)
{
//TODO check type for now just working with ints
TreeLeaf result;
result.number = var1.number + var2.number;
return result;
}
当我尝试将操作分配给 add(operation = add;
) 时出现错误。
我正在使用 XCode 7.3.
静态成员函数与成员函数不同。成员函数需要一个 class 的实例,而静态成员函数不需要,因此静态成员函数就像一个全局函数,但它的名称范围为 class。如果你想存储指向 add
的指针,那么你将拥有
TreeLeaf (*operation)(TreeLeaf,TreeLeaf);
然后
operation = add;
会是
operation = &TreeLeaf::add;