[英]How do I redefine a function within a function?
也许有一种更简单的方法可以执行此操作,但是我正在做的是编写一个包含两个Binary Search Trees的类。 我正在使用这些树来存储包含各个国家的奥运奖牌计数的结构。 这是结构:
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) {}
}
然后,我想为每个树添加一个新的国家。 我遇到的问题是我需要重载比较运算符(>,<,==,!=,<=,> =),以使Binary Search Tree方法起作用。 这并不是特别困难,但是需要对它们进行不同的定义。 当我添加到国家树时,我需要比较国家名称,而当我添加到排名树时,我需要比较排名。 所以我想做这样的事情:
void addNewCountry(string name, int goldMedalCount, int silverMedalCount, int bronzeMedalCount){
//Define comparison operators to compare based on rank
rankTree.add(CountryNode(name, goldMedalCount, silverMedalCount, bronzeMedalCount));
//Define comparison operators to compare based on country
countryTree.add(CountryNode(name, goldMedalCount, silverMedalCount, bronzeMedalCount));
}
通常,我会使用多种方法,但是在算术运算符重载的情况下,我实在无法做到。 谢谢。
我最终要做的是在操作符重载内执行一个指向函数的指针。 这样,我可以在需要时将指针重新分配给另一个函数,从而更改函数的内部结构,而无需通过常规通道重新定义它。 这是我所做的简短演示程序:
#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 = □
cout << variableFunction(10) << endl;
pointerSwitch = &doubleNum;
cout << variableFunction(10) << endl;
}
我们两次运行相同的函数,但修改了内部结构。 输出为:
100
20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.