将功能传递为无法在类中工作的参数

Passing functions as arguments not working inside a class

本文关键字:工作 参数 功能      更新时间:2023-10-16

在此示例中创建一个传递func的foo对象可以正常工作:

int func(int a) { return a; }
struct Foo {
  Foo( int (*func_ptr)(int) ) {};
};
Foo bar(func);

但是,尝试在另一类中创建一个foo对象没有:

class ThisIsCrap {
  Foo doesntWork(func);
};

如何在课堂内创建一个foo对象,就像我可以在班级外面一样?在没有编译的位上,错误是:"无法解析类型'func'"

预先感谢。

您可以使用a 默认成员initializer (dmi)为非静态类数据成员提供初始化程序:

int func(int a) { return a; }
struct Foo { Foo(int (*)(int)) {}; };
class ThisIsGreat {
  Foo one_way = func;     // DMI with copy-initialization syntax
  Foo another_way{func};  // DMI with list-initialization syntax
};

或当然可以使用构造函数:

class ThisIsSane {
  ThisIsSane()
      : third_way(func)   // constructor-initializer list
  {}
  Foo third_way;
};

语言律师的记录:在C 11中,ThisIsGreat不是骨料;在C 14中。

1,000归功于Kerrek SB。

class ThisWorks {
    Foo* working;
    ThisWorks() {
         working = new Foo(func);
    }
}