【问题标题】:Compile error when initializing class member std::function?初始化类成员 std::function 时编译错误?
【发布时间】:2015-07-31 19:04:32
【问题描述】:

我正在尝试使用 std::function 成员创建一个类:

# include<functional>

class Widget {
public:
  std::function<int(double)> call_foo;

  Widget(std::function<int(double)> call_func)
    : call_foo(call_func)
  {};

};

但是,当我尝试初始化类时,我的代码失败了:

const int f(double x){
  if(x > 5.0){
    return 22;
  }
  return 17;
}

int main()
{
  std::function<int(double)> f1 = f;
  Widget p(f1);

}

完整的错误集如下:

 tmp/ccDoRHCh.o: In function `__static_initialization_and_destruction_0(int, int)':
widget.cpp:(.text+0x109): undefined reference to `std::ios_base::Init::Init()'
widget.cpp:(.text+0x118): undefined reference to `std::ios_base::Init::~Init()'
/tmp/ccDoRHCh.o:(.rodata._ZTIPFidE[_ZTIPFidE]+0x0): undefined reference to `vtable for __cxxabiv1::__pointer_type_info'
/tmp/ccDoRHCh.o:(.rodata._ZTIFidE[_ZTIFidE]+0x0): undefined reference to `vtable for __cxxabiv1::__function_type_info'
/tmp/ccDoRHCh.o:(.eh_frame+0xab): undefined reference to `__gxx_personality_v0'
collect2: error: ld returned 1 exit status

我在启用 C++ 11 的情况下进行编译。

【问题讨论】:

  • 你做了#include &lt;functional&gt;吗?
  • @ex-bart 你是对的,我忘记了这个包含但代码仍然无法编译。似乎有某种链接器错误?
  • @Brian 我以为我已经构建了一个 SSCCE。我不确定除了函数 f 的函数体(它已经相当精简)之外,我如何才能使这个示例变得更小?上面的代码是我的整个文件,应该是自包含的。
  • 看起来你在命令行输入的是 gcc 而不是 g++。
  • 慢下来,阅读一些有关如何构建基本 C++11 程序的信息。例如,使用g++(不是gcc)。

标签: c++ c++11 function-pointers


【解决方案1】:

你可能忘记了

#include <functional>

或者你没有在 C++11 模式下编译。

【讨论】:

  • 你是对的,但即使包含了功能,这仍然无法编译。
猜你喜欢
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多