在不同的类继承级别调用函数链
Calling a chain of functions at different class inheritance levels
给定:
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;
}
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?