小编Sam*_*mps的帖子

C++类变量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?!

c++ lambda class c++11 std-function

5
推荐指数
1
解决办法
143
查看次数

标签 统计

c++ ×1

c++11 ×1

class ×1

lambda ×1

std-function ×1