C++ 如何在函数中重新定义函数?

C++ 如何在函数中重新定义函数?,c++,tree,C++,Tree,也许有一种更简单的方法可以做到这一点,但我正在编写一个由两个二进制搜索树组成的类。我用这些树来存储包含各国奥运奖牌数量的结构。下面是结构: struct Country{ string country; int rank; int gold; int silver; int bronze; Country(): country(""), rank(NULL), gold(NULL), silver(NULL), bronze(NULL){}

也许有一种更简单的方法可以做到这一点,但我正在编写一个由两个二进制搜索树组成的类。我用这些树来存储包含各国奥运奖牌数量的结构。下面是结构:

struct Country{
    string country;
    int rank;
    int gold;
    int silver;
    int bronze;

    Country(): country(""), rank(NULL), gold(NULL), silver(NULL), bronze(NULL){}
    Country(string ncountry, int ngold, int nsilver, int nbronze): country(ncountry), rank(NULL), gold(ngold), silver(nsilver), bronze(nbronze) {}
}

然后我想为每棵树添加一个新的国家。我遇到的问题是我需要重载比较运算符(>,我最后做的是在运算符重载中执行一个指向函数的指针。这样,我可以在需要时将指针重新分配给另一个函数,从而更改函数的内部结构,而无需通过常规通道重新定义。下面是我所做工作的简短演示程序:

#include <iostream>

using namespace std;

int (*pointerSwitch) (int) = NULL;

int square(int input){
    return input*input;
}

int doubleNum(int input){
    return input*2;
}

int variableFunction(int input){
    return pointerSwitch(input);
}

int main(){
    pointerSwitch = &square;
    cout << variableFunction(10) << endl;
    pointerSwitch = &doubleNum;
    cout << variableFunction(10) << endl;
}

从我最初说的开始,将树的模板参数设置为比较对象或类似的东西。将比较对象传递给
add
函数更有意义,尤其是在每次调用都使用相同类型的情况下。@JamesRoot感谢您的建议!我最终使用了不同的方法,但我学到了很多关于tem的知识在查看你建议的那一个时,请使用盘子!
#include <iostream>

using namespace std;

int (*pointerSwitch) (int) = NULL;

int square(int input){
    return input*input;
}

int doubleNum(int input){
    return input*2;
}

int variableFunction(int input){
    return pointerSwitch(input);
}

int main(){
    pointerSwitch = &square;
    cout << variableFunction(10) << endl;
    pointerSwitch = &doubleNum;
    cout << variableFunction(10) << endl;
}
100
20