在不同的类继承级别调用函数链
鉴于:
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++中正确实现方法链呢?
Given:
class Foo {
public:
void Method1();
}
class Bar extends Foo {
public:
Bar* Method2();
}
class Baz extends Bar {
public:
Baz* Method3();
}
So,
someObject *b = new Baz();
b->Method3()->Method2()->Method1();
This will work, as Baz()
contains all methods including Method2()
, Bar
contains Method1()
;
But, due to return type this seems to be a bad idea - when accessing simpler Method1()
at first inheritance level before calling more complex Method3()
, and having to keep this calls in single line..
b->Method1()->Method2()->Method(3); // will not work?
Also, someone told me that putting try.. catch.. throw
inside one of those Method's
will occasionally exit the chain without calling next method at wrong value. Is this true?
So how to properly implement method chaining in C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是虚拟方法的用途。从语法错误中我推测您是 C++ 新手
当您调用 TemplateMethod 时:
That's what virtual methods are for. From the syntax errors I gather that you are new to C++
When you call TemplateMethod: