调用不同类的继承层次
问题描述:
的功能链考虑:调用不同类的继承层次
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++中正确实现方法链?
答
这就是虚拟方法的用途。从语法错误我了解,你是新的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;
}
这不是有效的C++语法,顺便说一句。 – GManNickG 2011-04-22 22:11:19
**查找[CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)和哭泣。**它提供的功能与“虚拟”方法相同,但实现起来更复杂。 – CodeAngry 2014-02-06 12:00:47
@CodeAngry不知何故它是在habrahabr.ru同一天,你在这里提到它.. – 2014-02-08 17:21:55