Sam*_*mps 5 c++ lambda class c++11 std-function
需要在类中具有一个具有默认功能的函数变量,并且它的功能可以被覆盖.示例我喜欢/想要做什么(不幸的是失败):
#include <iostream>
#include <functional>
using namespace std;
class Base
{
public:
std::function<bool(void)> myFunc(){
cout << "by default message this out and return true" << endl;
return true;}
};
bool myAnotherFunc()
{
cout << "Another functionality and returning false" << endl;
return false;
}
int main()
{
Base b1;
b1.myFunc(); // Calls myFunc() with default functionality
Base b2;
b2.myFunc = myAnotherFunc;
b2.myFunc(); // Calls myFunc() with myAnotherFunc functionality
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道,这段代码不能编译.任何人都可以帮助解决这个问题,或推荐一些东西 如果有另一种方法来实现这个逻辑,则不需要是std :: function.也许应该使用lambda?!
改成:
class Base {
public:
std::function<bool()> myFunc = [](){
cout << "by default message this out and return true" << endl;
return true;
};
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |