c++ - C/C++函数作为参数

标签 c++

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是一棵通用树,它统计的是同一种形式的树在第二棵树中出现了多少次

enter image description here

我不明白的是第一个 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/

相关文章:

c++ - CMake:创建二进制 foo + 库 libfoo?

c++ - 获取两个最大值的索引

c++ - c++ 删除内存

C++ 主方法中的“ undefined reference ”

c++ - 从十进制转换的二进制中删除前导零

c++ - 如何正确删除那些指针?

c++ - 将捕获 lambda 作为函数指针传递

c++ - 触摸屏Qt应用

python - 错误 : stray '\' in program in macro definition

c++ - Accept() 在重复连接尝试时无限期地阻塞