方法 在调用基类方法后链接派生类方法
method chain a derived class method after calling a base class method
使用如下所示的类和导数,基类方法有没有办法返回派生类型的对象引用而不是它自己的类型,以便我可以在语法上将方法链接在一起?
假设对象A
具有方法a1,a2
和派生AD
添加一个方法ad1
那么如何制作有效的AD_instance.a1().a2().ad1();
方法链?
以下是有问题的两个类。忽略它的实际作用,方法链接是唯一重要的部分。
class AsyncWorker() {
pthread_t worker;
public:
AsyncWorker();
void *worker_run();
AsyncWorker& Detach() { /*code*/ return *this; }
AsyncWorker& Start() {
pthread_create(&worker, NULL, &AsyncWorker::worker_helper, this);
return *this;
}
static void *worker_helper(void *context) {
return ((AsyncWorker *)context)->worker_run();
}
};
class workerA : public AsyncWorker {
public:
int a;
workerA(int i) { a = i; }
void* worker_run() { ++a; sleep(1); }
workerA& other_method_i_want_to_chain() { return *this };
};
像这样被锁住。
workerA A(0);
A.Start().Detach().other_method_i_want_to_chain();
您可以在派生类中创建一个合适的重载,该重载调度到基类版本,但返回自身的对象:
class workerA {
// ...
workerA& Start() {
this->AsyncWorker::Start();
return *this;
}
workerA& Detach() {
this->AsyncWorker::Detach();
return *this;
}
// ...
};
希望这会让您更清楚地了解问题。
#include <iostream>
struct Base
{
virtual Base& foo() = 0;
};
struct Derived : Base
{
virtual Derived& foo()
{
std::cout << "Came to Derived::foo()n";
return *this;
}
void bar()
{
std::cout << "Came to Derived::bar()n";
}
};
int main()
{
Derived derived;
derived.foo().bar(); // OK. From the interface of Derived, foo()
// returns a Derived&.
Base& base = derived;
base.foo().bar(); // Not OK. From the interface of Base, foo()
// returns a Base&.
return 0;
}
相关文章:
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 从基类实例调用派生类方法而不进行强制转换
- C++ 使用派生类方法更改基类数据成员
- 将派生类方法与基类unique_ptr一起使用
- 使用基类对象访问派生的仅类方法
- C++:在派生类成员上调用基类方法
- 使用派生类C++方法的超类
- 无法访问派生类中的基类方法
- 哪个基类调用派生重写的方法?
- 有没有办法禁止派生类中的基类方法调用?
- 调用不属于基类的派生类函数的最佳方法是什么?
- 在派生类中调用基类方法,而无需指定基类名称
- 从库类扩展,然后如何让库调用派生类方法
- 如何模拟调用其基类方法的派生类
- 当应该调用派生类方法时,为什么要调用基类方法
- 从基类方法返回对派生类的引用
- 从具有相同基数的另一个派生类调用派生类的非 const 方法
- 无法从派生的一个方法调用基类方法
- 使用来自基类方法的派生类数据成员
- 传递指针或引用派生类,以便调用基类方法