将功能传递为无法在类中工作的参数
Passing functions as arguments not working inside a class
在此示例中创建一个传递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);
}
}
相关文章:
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 如何定义在用作函数参数时工作的类模板的转换
- C++20字符串文本模板参数工作示例
- C++中的可变参数模板及其工作原理
- std::bind,无法让具有单个参数的方法工作
- 隐式转换是否应该在模板参数的上下文中工作?
- 我不明白参数和参数如何协同工作
- 通过参数启用时,std::enabled_if 如何工作
- 当传递NULL作为参数时,函数重载是如何工作的
- GoogleTest 中的参数化测试无法按预期工作
- 此函数如何在不传递任何参数的情况下工作?
- 我的代码在作为参数传入 .begin() 时不起作用,但在我将 .begin() 转换为迭代器后工作
- C++11: 如何编写一个像 Get 一样工作的模板函数<tuple>...但是收到参数包?
- 参数传递和返回值如何在程序集级别的 x86 上的 C/C++ 中工作?
- 我可以更改将引用参数传递到指针中并使其正常工作的函数的输入(C、C++)吗?
- 工作函数重载如何使用可变参数解析?
- 宏参数的扩展如何在 c++ 中工作
- 错误太多参数无法正常工作
- 具有可变参数的std ::函数列表如何工作
- C++参数化构造函数使代码在传递大输入时停止工作