c++ - 你能声明一个成员函数并让它们做不同的事情吗?

标签 c++

我已经尝试了很多方法来解决这个问题,但都没有奏效。我想要实现的是这个。

我有这样一个类。

class Auton {
  public:
    int slot;
    const char * name;
    void run();
};

我想做的是让 run 函数做不同的事情。例如-

// The code below doesn't work, unfortunately :(

Auton one;
void one::run() {
  // Do something here
}

Auton two;
void two::run() {
 // Do something different here
}

这可能吗?

最佳答案

可以用 Lambda expressions .

示例:

class Auton {
public:
    int slot;
    const char * name;
    std::function<void()> run;
};

Auton one;
one.run = [] {
    // Do something here
};

Auton two;
two.run = [] {
    // Do something different here
};

关于c++ - 你能声明一个成员函数并让它们做不同的事情吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729873/

相关文章:

c++ - 如何使用 WinCrypt 和 C++ 以 PEM 格式导入私钥?

c++ - 为什么模板化类在初始化列表中识别另一个类的构造函数而不是在方法体中?

c++ - 我可以使用软件来测量信息发送的频率(以赫兹为单位)吗?

c++ - 不同编译器中的纯/常量函数属性

c++ - 是否可以在运行时确定对象选择的情况下使用 C++ 对象组合?

c++ - MFC - 仅最小化主 MDI 窗口

c++ - 在 C 或 C++ 中解析具有可变条目数的行(无提升)

c++ - C/C++ XMPP 库适用于 Android (NDK) 和 iOS

c++ - boost 继续恢复断言失败

c++ - Mingw32 中对 `SDL_main' 的 undefined reference