在不同的类继承级别调用函数链

Calling a chain of functions at different class inheritance levels

本文关键字:调用 函数 继承      更新时间:2023-10-16

给定:

class Foo {
 public:
   void Method1();
}
class Bar extends Foo {
 public:
   Bar* Method2();
}
class Baz extends Bar {
 public:
   Baz* Method3();
}

所以,

someObject *b = new Baz();
b->Method3()->Method2()->Method1();

这将起作用,因为Baz()包含所有方法,包括Method2()Bar包含Method1()

但是,由于返回类型的原因,这似乎是个坏主意——在调用更复杂的Method3()之前,在第一继承级别访问更简单的Method1()时,必须将这些调用保留在一行中。。

b->Method1()->Method2()->Method(3); // will not work?

另外,有人告诉我,将try.. catch.. throw放在其中一个Method's中偶尔会退出链,而不会以错误的值调用下一个方法。这是真的吗?

那么,如何在C++中正确地实现方法链接呢?

这就是虚拟方法的作用。从语法错误中我了解到你是C++的新手

struct Base
{
    virtual Base* One() { return this; };
    void TemplateMethod() { this->One(); }
};
struct Derived : public Base
{
    virtual Base* One() { /* do something */ return Base::One(); }
};

当您调用TemplateMethod:时

int main() 
{ 
      Base* d = new Derived();
      d->TemplateMethod(); // *will* call Derived::One() because it's virtual
      delete d;
      return 0;
}