bool isContainedSameForm(AG ag1, AG ag2){
if(isEmpty(ag2)) return false;
return isContainedSameForm(ag1->pH,ag2->pH) && isContainedSameForm(ag1->sH,ag2->sH);
};
int sameFormOcurrences(AG ag1,AG ag2,bool (*isContainedSameForm)(AG,AG)){
if(isEmpty(ag2)) return 0;
int ret=0;
if(isContainedSameForm(ag1,ag2)) ret=1;
return ret + sameFormOcurrences(ag1,ag2->pH,isContainedSameForm) + sameFormOcurrences(ag1,ag2->sH,isContainedSameForm);
};
int sameFormOcurrences( AG ag1, AG ag2){
return sameFormOcurrences(ag1,ag2,isContainedSameForm);
}
AG是一棵通用树,它统计的是同一种形式的树在第二棵树中出现了多少次
我不明白的是第一个 sameFormOcurrences 函数在参数中接收 isContainedSameForm 的目的。
难道只是改签名不改名字的一种方式吗? 如果它试图避免未定义的方法,那么上面已经声明的函数不是多余的吗?
最佳答案
这段代码不是以最好的风格编写的,函数指针参数和实现它的函数确实应该有不同的名称。现在如果参数声明有错别字,函数内部的代码会直接引用另一个函数,参数就会悄无声息地变得无用。
这样会好很多:
int countMatchingDescendants(AG ag1,AG ag2,bool (*matchCondition)(AG,AG))
{
if(isEmpty(ag2)) return 0;
int ret=0;
if(matchCondition(ag1,ag2)) ret=1;
return ret + countMatchingDescendants(ag1,ag2->pH,matchCondition) + countMatchingDescendants(ag1,ag2->sH,matchCondition);
}
bool isContainedSameForm(AG ag1, AG ag2)
{
if(isEmpty(ag2)) return false;
return isContainedSameForm(ag1->pH,ag2->pH) && isContainedSameForm(ag1->sH,ag2->sH);
}
int sameFormOcurrences( AG ag1, AG ag2)
{
return countMatchingDescendants(ag1,ag2,isContainedSameForm);
}
请注意,我只更改了标识符名称,而不是代码的结构(我还删除了函数体之外的无关分号)。但现在计数代码有一个通用名称,表明它实际上有多灵活。
通过更改顺序,我防止了通用计数代码意外引用具体实现的任何可能性。
关于c++ - C/C++函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32747958/