调用不同类的继承层次

问题描述:

的功能链考虑:调用不同类的继承层次

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();

但是,由于返回类型,这似乎是一个糟糕的主意 - 在访问第一个继承级别简单Method1()时调用复杂的前Method3()并且必须保持这种调用单行 ..

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

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

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

+4

这不是有效的C++语法,顺便说一句。 – GManNickG 2011-04-22 22:11:19

+1

**查找[CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)和哭泣。**它提供的功能与“虚拟”方法相同,但实现起来更复杂。 – CodeAngry 2014-02-06 12:00:47

+0

@CodeAngry不知何故它是在habrahabr.ru同一天,你在这里提到它.. – 2014-02-08 17:21:55

这就是虚拟方法的用途。从语法错误我了解,你是新的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; 
} 
+1

请注意,由于C++支持协变返回类型,所以'Derived :: One'可以返回一个Derived *'而不是'Base *',这可能是OP正在寻找的东西...... – ildjarn 2011-04-22 22:13:42

+1

我怀疑它:OP是担心,而是关于链接这些(所以实际的多态性是担心)。另外,在这种情况下你不能返回'Base :: One()'(没有... erm ...铸造 - 丑陋) – sehe 2011-04-22 22:17:15