C:如何将函数存储到变量中?
我觉得他们叫做医生? (有一阵子了)
基本上,我想存储指向一个变量中的函数的指针,所以我可以从命令行指定要使用的函数. 所有函数返回并获取相同的值. unsigned int func_1 (unsigned int var1) unsigned int func_2 (unsigned int var1) function_pointer = either of the above? 所以我可以通过去:function_pointer(my_variable)来调用它? 编辑: class Config { public: unsigned static int (*current_hash_function)(unsigned int); }; Config.cpp: #include "Config.h" #include "hashes.h" unsigned static int (*current_hash_function)(unsigned int) = kennys_hash_16; hashes.h: unsigned int kennys_hash(unsigned int out); unsigned int kennys_hash_16(unsigned int out); hashes.cpp: just implements the functions in the header main.cpp中: #include "Config.h" #include "hashes.h" // in test_network: unsigned int hashed = Config::current_hash_function(output_binary); //in main(): else if (strcmp(argv[i],"-kennys_hash_16") == 0) { Config::current_hash_function = kennys_hash_16; } else if (strcmp(argv[i],"-kennys_hash_8") == 0) { Config::current_hash_function = kennys_hash; } 我得到的错误: g++ -o hPif src/main.o src/fann_utils.o src/hashes.o src/Config.o -lfann -L/usr/local/lib Undefined symbols: "Config::current_hash_function",referenced from: test_network() in main.o // the place in the code I've selected to show auto_test_network_with_random_data(unsigned int,unsigned int,unsigned int)in main.o generate_data(unsigned int,unsigned int)in main.o _main in main.o // the place in the code I've selected to show _main in main.o // the place in the code I've selected to show generate_train_file() in fann_utils.o ld: symbol(s) not found collect2: ld returned 1 exit status make: *** [hPif] Error 1 解决方法
你最简单的就是
unsigned int (*pFunc)(unsigned int) = func_1; 这是一个裸函数指针,它不能用于指向除自由函数之外的任何内容. 如果您的编译器支持C 0x auto关键字,则可以减少痛苦: auto pFunc = func_1; 在任何情况下,您都可以调用该函数 unsigned int result = pFunc(100); 还有许多其他选项可以提供通用性,例如: >您可以使用boost :: function与任何C编译器 这些可以用于指向可以使用适当签名调用的任何实体(实际上是实现一个称为函子的operator()的对象). 更新(解决更新的问题) 您的直接问题是您尝试使用Config :: current_hash_function(您声明很好)但无法定义它. 这定义了一个与类Config中的任何内容无关的函数的全局静态指针: unsigned static int (*current_hash_function)(unsigned int) = kennys_hash_16; 这就是你所需要的: unsigned int (*Config::current_hash_function)(unsigned int) = kennys_hash_16; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |