【问题标题】:Calling a chain of functions at different class inheritance levels在不同的类继承级别调用一系列函数
【发布时间】:2011-04-22 22:07:24
【问题描述】:

给定:

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 偶尔会退出链,而不会以错误的值调用 next 方法。这是真的吗?

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

【问题讨论】:

  • 顺便说一句,这不是有效的 C++ 语法。
  • 查找 CRTP 并哭泣。 它提供相同的功能,但没有 virtual 方法,但实现起来要复杂得多。
  • @CodeAngry 不知何故它在你在这里提到它的同一天出现在 habrahabr.ru..
  • @kagali-san 大约每年我都会四处搜索,看看是否出现了一种新的比 CRTP 更简单的非虚拟函数技术。每年,我都会回到 CRTP。 :)

标签: c++ method-chaining


【解决方案1】:

这就是虚方法的用途。从语法错误中我了解到您是 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;
}

【讨论】:

  • 请注意,Derived::One 可以返回 Derived* 而不是 Base*,因为 C++ 支持协变返回类型,这可能是 OP 正在寻找的...
  • 我对此表示怀疑:相反,OP 担心将这些链接起来(因此担心的是实际的多态性)。此外,在这种情况下,你不能返回 Base::One()(没有......呃......铸造 - 丑陋)
猜你喜欢
  • 1970-01-01
  • 2015-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
  • 2012-12-09
相关资源
最近更新 更多