微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)来调用它?

编辑:
根据@ larsmans的建议,我已经得到了:
config.h中:

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编译器
>使用编译器实现C 0x的功能,可以使用std :: function

这些可以用于指向可以使用适当签名调用的任何实体(实际上是实现一个称为函子的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;

原文地址:https://www.jb51.cc/c/113850.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐