您可以声明会员功能并使他们做不同的事情吗?

Can you declare a member function and make them do different things?

本文关键字:他们 不同的事 声明 功能      更新时间:2023-10-16

我已经尝试了多种方法来解决这个问题,但是它们都没有起作用。我要实现的是。

我有这样的课程。

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表达式。

示例:

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
};

不幸的是。可能的是:

class Auton {
public:
    // ...
    virtual void run();
};
class AutonOne : public Auton {
public:
    // ...
    void run() override
    {
        // Do something
    }
};
class AutonTwo : public Auton {
public:
    // ...
    void run() override
    {
        // Do something different
    }
};
AutonOne one;
AutonTwo two;

在此处了解有关此信息的更多信息:为什么我们需要C ?

中的虚拟功能