C++ 重新定义特定对象的类方法

C++ Redefining Class Method for Specific Objects

本文关键字:对象 类方法 定义 新定义 C++      更新时间:2023-10-16

我有一个类foo,它有一个方法doesSomething() .我构造了该类的多个对象,但对于一些特定的对象,我希望doesSomething()做其他事情。构造后如何动态地重新定义该方法的主体?

我相信这正是我正在寻找的,但它是用Java的。

如果要"覆盖"以前的类定义,可以使用虚函数,并使用派生类。

这里有一些例子,特别是在"虚拟成员"标题下。

祝你好运。

struct nasty_object {
  nasty_object() 
  : _something_do { std::bind(&nasty_object::normal_thing, this) }
  {
  }
  void normal_thing() {
    // the stuff to do in the default case
  }
  void do_other_thing() {
    // the stuff to do in the alternate case
  }
  void do_something() {
    if(_something_do) {
      _something_do();
    }
  }
  // replace the meaning of 'do_something()'
  void set_do_something(std::function<void()> f)
  {
    _something_do(std::move(f));
  }
private:
  std::function<void()> _something_do;
};

现在您可以在运行时创建对象并更改 do_something() 的含义,如下所示

auto n1 = nasty_object{};
auto n2 = nasty_object{};
auto n3 = nasty_object{};
n2.set_do_something(std::bind(&nasty_object::do_other_thing, &n2));
n3.set_do_something([&n3] {
  // do something totally different!
});
n1.do_something(); // does something
n2.do_something(); // does the other thing
n3.do_something(); // does whatever was in your lambda

注意:仅仅因为您可以使用 c++ 执行此操作并不意味着您应该这样做。这种不负责任的行为最好留给剧本骑师和其他人,没有任何好处。

在C++中,对象没有对方法的引用,它们具有对"虚拟函数表"又名"类"的引用。 因此,您需要让另一个类参与进来,以您设想的方式进行操作。但是你也说你想在对象被构造后改变它 - 这意味着你不能使用虚函数来做到这一点。相反,您应该使用函数指针,甚至只是一个简单的布尔值:

class C {
    bool isSpecial;
    void doesSomethingNormal() { ... }
    void doesSomethingSpecial() { ... }
    void doesSomething() { 
              if (isSpecial) 
                  doesSomethingSpecial();
              else doesSomethingNormal();
    }
};